package com.hutao.manage.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.hutao.manage.component.Config;
import com.hutao.manage.component.MyConfig;
import com.hutao.manage.datasource.TargetDataSource;
import com.hutao.manage.pojo.FirstLevelMedical;
import com.hutao.manage.pojo.HospNoteVersion;
import com.hutao.manage.pojo.LeftMenuPojo;
import com.hutao.manage.pojo.MedicalResource;
import com.hutao.manage.pojo.MedicalResourcePic;
import com.hutao.manage.pojo.MrPageType;
import com.hutao.manage.pojo.ScanFile;
import com.hutao.manage.pojo.TreatmentTrace;
import com.hutao.manage.pojo.UploadScan;
import com.hutao.manage.pojo.UploadScanFile;
import com.hutao.manage.pojo.cust.BloodTransfusion;
import com.hutao.manage.pojo.cust.BloodTransfusionInfo;
import com.hutao.manage.pojo.cust.HospitalInfection;
import com.hutao.manage.pojo.cust.HospitalInfectionInfo;
import com.hutao.manage.pojo.cust.HospitalizationChangeOffice;
import com.hutao.manage.pojo.cust.HospitalizationChangeOfficeInfo;
import com.hutao.manage.pojo.cust.HospitalizationCost;
import com.hutao.manage.pojo.cust.HospitalizationCureInfo;
import com.hutao.manage.pojo.cust.HospitalizationDiagnosis;
import com.hutao.manage.pojo.cust.HospitalizationDiagnosisInfo;
import com.hutao.manage.pojo.cust.HospitalizationDrugAllergyInfo;
import com.hutao.manage.pojo.cust.HospitalizationIntensiveCareInfo;
import com.hutao.manage.pojo.cust.HospitalizationNoteBasic;
import com.hutao.manage.pojo.cust.HospitalizationNurseRecordInfo;
import com.hutao.manage.pojo.cust.HospitalizationOperation;
import com.hutao.manage.pojo.cust.HospitalizationOperationInfo;
import com.hutao.manage.pojo.cust.HospitalizationPressureSoreInfo;
import com.hutao.manage.pojo.cust.MedicalRecordPrinterImage;
import com.hutao.manage.pojo.cust.MedicalRecordPriter;
import com.hutao.manage.pojo.cust.ObstetricalRecord;
import com.hutao.manage.pojo.cust.ObstetricalRecordInfo;
import com.hutao.manage.query.MedRecordQuery;
import com.hutao.manage.query.MedTraceQuery;
import com.hutao.manage.query.MedVisitUrgeQuery;
import com.hutao.manage.query.MedicalSearchQuery;
import com.hutao.manage.service.BaseInfoService;
import com.hutao.manage.service.BasicInfoService;
import com.hutao.manage.service.FirstLevelMedicalService;
import com.hutao.manage.service.HospNoteBasicJsonService;
import com.hutao.manage.service.HospitalNoteVersionService;
import com.hutao.manage.service.MedRecordService;
import com.hutao.manage.service.MedicalRecordService;
import com.hutao.manage.service.MedicalResourcePicService;
import com.hutao.manage.service.MedicalResourceService;
import com.hutao.manage.service.MrPageTypeService;
import com.hutao.manage.service.ScanFileService;
import com.hutao.manage.service.TreatmentTraceService;
import com.hutao.manage.service.UploadFileService;
import com.hutao.manage.util.CookieUtils;
import com.hutao.manage.util.CreateFileUtil;
import com.hutao.manage.util.DateUtil;
import com.hutao.manage.util.ExcelUtil;
import com.hutao.manage.util.ExceptionLog;
import com.hutao.manage.util.ExceptionUtil;
import com.hutao.manage.util.FileUtil;
import com.hutao.manage.util.GuidUtil;
import com.hutao.manage.util.HttpClientUtil;
import com.hutao.manage.util.JsonUtil;
import com.hutao.manage.util.JsonUtils;
import com.hutao.manage.util.ListUtil;
import com.hutao.manage.util.MD5;
import com.hutao.manage.util.PDFUtil;
import com.hutao.manage.util.Page;
import com.hutao.manage.util.Result;
import com.hutao.manage.util.StringUtil;
import com.hutao.manage.util.disk.DiskManageUtil;



@Controller
@RequestMapping("/medrecord")
public class MedrecordController {
	private Logger log = LoggerFactory.getLogger(MedrecordController.class);

	@Autowired
	private MedRecordService medRecordService;
	
	@Autowired
	private UploadFileService uploadFileService;
	
	@Autowired  
    private Config conf; 
	
	@Autowired  
	private MyConfig myConfig;
	
	@Autowired
    private ScanFileService scanFileService; 
	
	@Autowired
	private MedicalResourceService medicalResourceService;
	
	@Autowired
	private MedicalResourcePicService medicalResourcePicService;
	
	@Autowired
	private MrPageTypeService mrPageTypeService;
	
	@Autowired BasicInfoService basicInfoService;
	
	@Autowired BaseInfoService baseInfoService;
	
	@Autowired
	private TreatmentTraceService treatmentTraceService;
	
	@Autowired
	private MedicalRecordService medicalRecordService;
	
	@Autowired
	private HospitalNoteVersionService hospitalNoteVersionService;
	
	//操作住院json信息service
	@Autowired
	private HospNoteBasicJsonService hospNoteBasicJsonService;
	
	@Autowired
	private FirstLevelMedicalService firstLevelMedicalService;
	
	@Autowired
	private Config config;
	
	
	
	@RequestMapping("/queryMedrecordImage")
	public String queryMedrecordImage(MedRecordQuery params, Model model){
		LeftMenuPojo leftMenu = LeftMenuPojo.GetLeftMenu("query_module");
		String leftMenuJson = JsonUtils.objectToJson(leftMenu);
		List<Map<String,Object>> hospitalizationNotes = medRecordService.getHospitalizationNoteList(params);
		int count = medRecordService.getHospitalizationNoteCount(params);
		params.setTotalCounts(count);
		model.addAttribute("hospitalizationNotes", hospitalizationNotes);
		model.addAttribute("leftMenuJson", leftMenuJson);
		model.addAttribute("medRecordQuery", params);
		
		return "query/medicalImageQuery.page";
	}
	
	/**
	 * 通过ajax请求查询住院病案
	 * @param params
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/queryMedrecordOfPrinterByAjax",method=RequestMethod.GET)
	@ResponseBody
	public Result queryMedrecordOfPrinterByAjax(MedRecordQuery params, Model model, HttpServletResponse response){
		response.setHeader("Access-Control-Allow-Origin", "*");
		Map<String,Object> resultMap = new HashMap<String, Object>();
		
		System.out.println(params.getName());
		List<Map<String,Object>> hospitalizationNotes = medRecordService.getHospitalizationNoteOfPrinterList(params);
		int count = medRecordService.getHospitalizationNoteCountOfPrinter(params);
		
		params.setTotalCounts(count);
		resultMap.put("count", count);
		resultMap.put("hospitalizationNotes", hospitalizationNotes);
		resultMap.put("medRecordQuery", params);
		Result result= new Result(true, "查询成功!",resultMap);
		
		return result;
	}
	
	
	
	@RequestMapping("/exportMedrecordToExcel")
	public void exportMedrecordToExcel(MedRecordQuery params,HttpServletResponse response){
		List<Map<String,Object>> scanWorkMapList=new ArrayList<>();
		
		try {
			response.setContentType("octets/stream");
	        String excelName = "病案打印";  
			//转码防止乱码  
			response.addHeader("Content-Disposition", "attachment;filename="+new String(excelName.getBytes("gb2312"), "ISO8859-1" )+".xls");  
			//通过response获取文件输出流
			OutputStream out = response.getOutputStream();
		
			//查询数据
			scanWorkMapList=medRecordService.getHospitalizationNoteOfPrinterList(params);
			System.out.println(scanWorkMapList.size());
			String title="病案打印";
			String[] header={"姓名","身份证号","就诊标示记录","打印原因","打印份数","出院时间","操作"};
			ExcelUtil.exportExcel(out, title, header, scanWorkMapList);
			
		} catch (Exception e) {
			e.printStackTrace();
			
		}
	}
	

	@RequestMapping(value="/queryMedrecordImageOfPrinterByAjax", method=RequestMethod.GET)
	@ResponseBody
	public Result queryMedrecordImageOfPrinterByAjax(MedicalRecordPriter medicalRecordPriter, Model model, HttpServletResponse response){
		response.setHeader("Access-Control-Allow-Origin", "*");
		Map<String,Object> resultMap = new HashMap<String, Object>();
		
		List<Map<String,Object>> hospitalizationNotes = medRecordService.getHospitalizationNoteByFirstGuid(medicalRecordPriter.getFirstGuid());
		
		List<MedicalRecordPrinterImage> printerImages = medRecordService.getMedicalRecordPrinterImages(medicalRecordPriter.getFirstGuid(),medicalRecordPriter.getPrinterType());
	
		/*	resultMap.put("hospitalizationNotes", hospitalizationNotes);*/
		resultMap.put("printerImages", printerImages);
		Result result= new Result(true, "查询成功!",resultMap);
		
		return result;
	}
	
	@RequestMapping("/showMedrecordImage")
	public String showMedrecordImage(String firstGuid, Model model){
		List<Map<String,Object>> hospitalizationNotes = medRecordService.getHospitalizationNoteByFirstGuid(firstGuid);
		model.addAttribute("hospitalizationNotes", hospitalizationNotes);
		List<Map<String,Object>> scanFiles = medRecordService.getScanFiles(firstGuid);
		model.addAttribute("scanFiles", scanFiles);
		model.addAttribute("count",scanFiles.size());
		model.addAttribute("hospitalizationNoteResourceUrl", conf.getHospitalizationNoteResourceUrl());
		
		return "medrecord/medRecordImageShow.simple";
	}
	
	@RequestMapping("/manageMedrecordImage")
	public String showMedrecordManage(String firstGuid, Model model){
		List<Map<String,Object>> hospitalizationNotes = medRecordService.getHospitalizationNoteByFirstGuid(firstGuid);
		model.addAttribute("hospitalizationNotes", hospitalizationNotes);
		List<Map<String,Object>> scanFiles = medRecordService.getScanFiles(firstGuid);
		
		DiskManageUtil.fileHashStorageRootUrl(scanFiles, 
				config.getConfigFileStorageAllDisk(),
				config.getUploadResourcePath(), 
				config.getHospitalizationNoteResourceUrl(),
				firstGuid
				);
		
		model.addAttribute("scanFiles", scanFiles);
		model.addAttribute("count",scanFiles.size());
		model.addAttribute("firstGuid",firstGuid);
		model.addAttribute("hospitalizationNoteResourceUrl", conf.getHospitalizationNoteResourceUrl());
		
		return "medrecord/medRecordImageManage.simple";
	}
	
	@RequestMapping("/manageMedrecordUploadImage")
	public String manageMedrecordUploadImage(String firstGuid, Model model){
		List<Map<String,Object>> hospitalizationNotes = medRecordService.getHospitalizationNoteByFirstGuid(firstGuid);
		model.addAttribute("hospitalizationNotes", hospitalizationNotes);
		List<Map<String,Object>> scanFiles = medRecordService.getScanFiles(firstGuid);
		model.addAttribute("scanFiles", scanFiles);
		model.addAttribute("count",scanFiles.size());
		model.addAttribute("hospitalizationNoteResourceUrl", conf.getHospitalizationNoteResourceUrl());
		
		return "medrecord/medRecordImageManage.simple";
	}
	
	@ResponseBody
	@RequestMapping("/removeMedrecordImage")
	public Result removeMedrecordImage(String firstGuid, String fileHash, Model model){
		int result = 0;
		try{
			result = medRecordService.removeMedRecordImage(firstGuid, fileHash);
			
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			result = -1;
		}
		if(result == 2){
			return new Result(true, "删除病案图片成功", result);
		}else{
			return new Result(false, "删除病案图片失败", result);
		}
		
	}
	
	
	@ResponseBody
	@RequestMapping("/removeMedrecordImageList")
	public Result removeMedrecordImageList(String firstGuid, String fileHashs, Model model){
		if(StringUtils.isNotEmpty(fileHashs) && StringUtils.isNotEmpty(firstGuid)){
			for (String fileHash : fileHashs.split(",")) {
				medRecordService.removeMedRecordImage(firstGuid, fileHash);
			}
		}
		
		List<Map<String,Object>> scanFiles = medRecordService.getScanFiles(firstGuid);
		return new Result(true, "删除病案图片成功", scanFiles.size());
	}
	
	
	@TargetDataSource(name="ds1")
	@Transactional(propagation=Propagation.REQUIRED)
	@RequestMapping(value = "/uploadFilesByFirstGuid", method = RequestMethod.POST)
	public String uploadFilesByFirstGuid(@RequestParam("files")MultipartFile[] files, @RequestParam("firstGuid")String firstGuid, 
				HttpServletRequest request) throws Exception {
		try {
			String currentUser = CookieUtils.getCookieValue(request, "userName");
			UploadScan uploadScan=null;
			ScanFile scanFile=null;
			Integer uploadScanid=null;
			UploadScanFile uploadScanFile=null;
			MedicalResource medicalResource = null;
			MedicalResourcePic medicalResourcePic = null;
			int i=1;
			
			if (files != null && files.length > 0) {
				for (MultipartFile multipartFile : files) {
					//文件原名称
					String originalFilename=multipartFile.getOriginalFilename();
					
					String fileType=originalFilename.substring(originalFilename.lastIndexOf(".")+1);
					if(StringUtils.isEmpty(fileType)){
						continue;
					}
					if(!fileType.equalsIgnoreCase("png") && !fileType.equalsIgnoreCase("jpg") && !fileType.equalsIgnoreCase("jpeg")){
						continue;
					}
					
					
					//文件流Hash（100位）
					String hashStr = new StringBuffer(GuidUtil.get36SystemHash(new String(multipartFile.getBytes()))).reverse().toString();
					//获取文件后缀名
					String fileSuffixes = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
					long fileSize = multipartFile.getSize();
					String fileSizeHashStr = GuidUtil.get36SystemHash(fileSize);
					
					//文件Hash
					String fileHash = new StringBuffer(hashStr).append(fileSizeHashStr).toString();
					//判断是否已经有相关文件，有直接跳过
					if(medRecordService.medicalResourceIsExist(firstGuid, fileHash)){
						continue;
					}
					
					//添加uploadScan
					if (i<=1) {
						uploadScan = new UploadScan();
						uploadScan.setCreateUserId(currentUser);
						//uploadScan.setHospitalId(1);
						//uploadScan.setStatus(1);
						uploadScan.setCreateDate(new Date());
						uploadScan.setUploadDate(new Date());
						uploadScan.setFirstLevelMedicalGuid(firstGuid);
						//uploadScan.setComment("12344");
						uploadFileService.addUploadScan(uploadScan);
						uploadScanid=uploadScan.getId();
						i++;
					}
					
					//if (!scanFileService.isFileExist(fileHash)) {
						scanFile = new ScanFile();
						scanFile.setFileHash(fileHash);
						scanFile.setOriginalName(originalFilename);
						String localPath = GuidUtil.getLocalPath(hashStr);
						String remoteUrl = GuidUtil.getRemoteUrl(hashStr);
						//文件摘要后92位  文件摘要hash值 + 文件大小的5位hash值  
						 hashStr = hashStr.substring(8)+fileSizeHashStr.substring(0, 5);
						//文件保存路径
						String filePath = conf.getUploadResourcePath() + localPath;
						
						//判断文件是否已经存在本地
						if (!DiskManageUtil.isExistsFileInAllDisk(config.getConfigFileStorageAllDisk(), filePath + hashStr+"."+fileSuffixes)) {
							File destFile = new File(filePath, hashStr+"."+fileSuffixes);
							
							if (!destFile.exists()) {
								File destDir = new File(filePath);
								if (!destDir.exists()) {
									destDir.mkdirs();
								}
								
								multipartFile.transferTo(destFile);
							}
						}
						
						scanFile.setCreateDate(new Date());
						scanFile.setFileType(fileSuffixes);
						scanFile.setFileName(hashStr+"."+fileSuffixes);
						scanFile.setFileUrl(remoteUrl);
						uploadFileService.addScanFile(scanFile);
						uploadFileService.addScanFile(scanFile);
					//}
					
					uploadScanFile = new UploadScanFile();
					uploadScanFile.setFileHash(fileHash);
					uploadScanFile.setOriginalFileName(originalFilename);
					uploadScanFile.setUploadScanId(uploadScanid);
					uploadFileService.addUploadScanFile(uploadScanFile);
					
//					uploadScanFile = new UploadScanFile();
//					uploadScanFile.setFileHash(fileHash);
//					uploadScanFile.setOriginalFileName(originalFilename);
//					uploadScanFile.setUploadScanId(uploadScanid);
//					uploadFileService.addUploadScanFile(uploadScanFile);
					
					medicalResource=new MedicalResource();
					medicalResource.setFirstLevelMedicalId(firstGuid);
					medicalResource.setMedicalResourceTypeId(1);
					medicalResource.setCreateDate(new Date());
					
					medicalResourceService.insert(medicalResource);
					
					medicalResourcePic=new MedicalResourcePic();
					medicalResourcePic.setFileHash(fileHash);
					medicalResourcePic.setMedicalResourceId(medicalResource.getId());
					medicalResourcePicService.insert(medicalResourcePic);
					
					
				}
			}
			
			TreatmentTrace trace = new TreatmentTrace();
			trace.setTraceDate(new Date());
			trace.setTreatmentGuid(firstGuid);
			trace.setUserId(currentUser);
			treatmentTraceService.addMedicalTrace(trace,TreatmentTrace.VISIT_SCAN);
			
			List<Integer> traceIdLists = treatmentTraceService.selectTraceByGuidAndCode(firstGuid, TreatmentTrace.VISIT_PAGINATION);
			if(CollectionUtils.isNotEmpty(traceIdLists)){
				for (Integer id : traceIdLists) {
					treatmentTraceService.deleteById(id);
				}
				
			}
			
		} catch (Exception e) {
			e.getStackTrace();
			throw e;
		}
		return "redirect:/medrecord/manageMedrecordImage?firstGuid="+firstGuid;
	}
	
	@RequestMapping("/queryPaginationMedrecordImage")
	public String queryPaginationMedrecordImage(MedRecordQuery params,Model model){
		LeftMenuPojo leftMenu = LeftMenuPojo.GetLeftMenu("scan_upload");
		String leftMenuJson = JsonUtils.objectToJson(leftMenu);
		
		List<Map<String,Object>> hospitalizationNotes = new ArrayList<Map<String,Object>>();
		
		if(!params.IsPropertyEmpty()){
			hospitalizationNotes = medRecordService.getHospitalizationNoteList(params);
			int count = medRecordService.getHospitalizationNoteCount(params);
			params.setTotalCounts(count);
		}
		
		model.addAttribute("hospitalizationNotes", hospitalizationNotes);
		model.addAttribute("leftMenuJson", leftMenuJson);
		model.addAttribute("medRecordQuery", params);
		return "query/medicalImagePaginationQuery.page";
	}
	
	@ResponseBody
	@RequestMapping("/addPaginationTreatementTrace")
	public boolean addPaginationTreatementTrace(String firstGuid,HttpServletRequest request){
		try {
			
			System.out.println(medRecordService.isHaveNopage(firstGuid));
			
			if(medRecordService.isHaveNopage(firstGuid)>0){
				return true;
			}
			//如果有还未编页的数据,不添加编页记录
			String currentUser = CookieUtils.getCookieValue(request, "userName");
			TreatmentTrace treatmentTrace = new TreatmentTrace();
			treatmentTrace.setUserId(currentUser);
			treatmentTrace.setTreatmentGuid(firstGuid);
			treatmentTraceService.addMedicalTrace(treatmentTrace,TreatmentTrace.VISIT_PAGINATION);
			
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	@RequestMapping("/paginationMedrecordImages")
	public String paginationMedrecordImages(String firstGuid,MedRecordQuery params,String paginationStatus, Model model,HttpServletRequest request){
		List<Map<String,Object>> hospitalizationNotes = medRecordService.getHospitalizationNoteByFirstGuid(firstGuid);
		model.addAttribute("hospitalizationNotes", hospitalizationNotes);
		if(StringUtils.isEmpty(paginationStatus)){
			paginationStatus="1";
		}
//		String currentUser = CookieUtils.getCookieValue(request, "userName");
//		TreatmentTrace treatmentTrace = new TreatmentTrace();
//		treatmentTrace.setUserId(currentUser);
//		treatmentTrace.setTreatmentGuid(firstGuid);
//		treatmentTraceService.addMedicalTrace(treatmentTrace,TreatmentTrace.VISIT_PAGINATION);
		List<Map<String,Object>> scanFiles = scanFileService.getPaginationScanFilesByFirstGuidAndPagination(firstGuid,paginationStatus);
		
		DiskManageUtil.fileHashStorageRootUrl(scanFiles, 
				config.getConfigFileStorageAllDisk(),
				config.getUploadResourcePath(), 
				config.getHospitalizationNoteResourceUrl(),
				firstGuid
				);
		
		model.addAttribute("scanFiles", scanFiles);

		//编页的所有标签 通过sort_code排序
		List<MrPageType> mrPageTypes = mrPageTypeService.getMrPageTypes();
		model.addAttribute("mrPageTypes", mrPageTypes);
		model.addAttribute("mrPageSizes", mrPageTypes.size());
		
		
		List<Map<String,Object>> mrPageTypesOfPagination = mrPageTypeService.getMrPageTypesOfPaginationCountByFirstGuid(firstGuid);
		Map<Integer, Map<String,Object>> mrPageTypesOfPaginationMap = new HashMap<Integer, Map<String,Object>>();
		
		for (Map<String, Object> mrPageTypeOfPagination : mrPageTypesOfPagination) {
			mrPageTypesOfPaginationMap.put((Integer)mrPageTypeOfPagination.get("mr_page_type"), mrPageTypeOfPagination);
		}
		
		model.addAttribute("params", params);
		//System.out.println(mrPageTypesOfPaginationMap);
		model.addAttribute("paginationStatus", paginationStatus);
		model.addAttribute("mrPageTypesOfPaginationMap", mrPageTypesOfPaginationMap);
		model.addAttribute("hospitalizationNoteResourceUrl", conf.getHospitalizationNoteResourceUrl());
		model.addAttribute("newDate", new Date().getTime());
		
		return "medrecord/medRecordImagePagination.simple";
	}
	
	@RequestMapping("/getMedicalFileListAjax")
	@ResponseBody
	public Result getMedicalFileList(String firstGuid, HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		
		Result result = null;
		try {
			Map map = new HashMap();
			map.put("hospitalizationNoteResourceUrl", conf.getHospitalizationNoteResourceUrl());
			//1代表已经编页的
			List<Map<String,Object>> scanFiles = scanFileService.getPaginationScanFilesByFirstGuidAndPagination(firstGuid, "2");
			map.put("scanFiles", scanFiles);
			result = new Result(true, "查询成功!", map);
		} catch (Exception e) {
			log.error("------查询编页异常-----" + ExceptionUtil.getStackTrace(e));
		}
		
		return result;
	}
	
	
	@ResponseBody
	@RequestMapping("/scanFilePaginationCount")
	public Map<String,Object> scanFilePaginationCount(String firstGuid){
		Map<String,Object> map = new HashMap<>();
		int scanFileCount = scanFileService.getScanFilePaginationCount(firstGuid, null);
	 	int unPaginationFileCount = scanFileService.getScanFilePaginationCount(firstGuid, "1");
	 	map.put("scanFileCount", scanFileCount);
	 	map.put("unPaginationFileCount", unPaginationFileCount);
	 	return map;
	}
	
	
	
	@RequestMapping("/paginationMarkMedrecordImages")
	public String paginationMarkMedrecordImages(String firstGuid, String applyName,Model model,HttpServletRequest request){
		List<Map<String,Object>> hospitalizationNotes = medRecordService.getHospitalizationNoteByFirstGuid(firstGuid);
		model.addAttribute("hospitalizationNotes", hospitalizationNotes);
		if(StringUtils.isNotEmpty(applyName)){
			try {
				applyName = URLDecoder.decode(applyName, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}else{
			applyName =	CookieUtils.getCookieValue(request, "userName");
		}
		
		
		
		
		//{fileName=41hozjlk28b5v0hfickfia02aj8pdumvk1v1ae7jt7yqfhf769oyjs3c77f10ajzm0jjipo1o50a0sgcaw5igtfnux31093x2.jpg, mr_page_type_id=2, fileHash=v90ffx5c41hozjlk28b5v0hfickfia02aj8pdumvk1v1ae7jt7yqfhf769oyjs3c77f10ajzm0jjipo1o50a0sgcaw5igtfnux31093x2, fileUrl=v9/0f/fx/5c/, fileType=jpg}
		
		List<Map<String,Object>> scanFiles = scanFileService.getPaginationScanFilesByFirstGuid(firstGuid);
		if(CollectionUtils.isNotEmpty(scanFiles)){
			for (Map<String, Object> scanFil : scanFiles) {
				String fileName =  scanFil.get("fileName")==null?"":(String) scanFil.get("fileName");
				String fileUrl = scanFil.get("fileUrl")==null?"":(String) scanFil.get("fileUrl");
				String fileHash= scanFil.get("fileHash")==null?"":(String) scanFil.get("fileHash");
				String secret=	MD5.md5(applyName+fileHash);
				// 调用sso生成图片水印
				Map<String, String> cachePicParam = new HashMap<>();
				cachePicParam.put("fileName", fileUrl + fileName);
				cachePicParam.put("secret", secret);
				try {
					String preWatermark=conf.getWaterMarkPre();
					
					String signature=URLEncoder.encode(preWatermark+"--"+applyName, "utf-8");
					cachePicParam.put("signature", signature);
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				String cachePicJson = HttpClientUtil.doPost(conf.getSeekMarkPicUrl(),
						cachePicParam);
				if(StringUtils.isNotEmpty(cachePicJson)){
					Result result = JsonUtils.jsonToPojo(cachePicJson, Result.class);
					if(result.isSuccess()){
						scanFil.put("markPicUrl", result.getData());
					}
				}
				
				
			}
		}
		model.addAttribute("scanFiles", scanFiles);
		
		List<MrPageType> mrPageTypes = mrPageTypeService.getMrPageTypes();
		List<Map<String,Object>> mrPageTypesOfPagination = mrPageTypeService.getMrPageTypesOfPaginationCountByFirstGuid(firstGuid);
		model.addAttribute("mrPageTypes", mrPageTypes);
		Map<Integer, Map<String,Object>> mrPageTypesOfPaginationMap = new HashMap<Integer, Map<String,Object>>();
		for (Map<String, Object> mrPageTypeOfPagination : mrPageTypesOfPagination) {
			mrPageTypesOfPaginationMap.put((Integer)mrPageTypeOfPagination.get("mr_page_type"), mrPageTypeOfPagination);
		}
		model.addAttribute("mrPageTypesOfPaginationMap", mrPageTypesOfPaginationMap);
		model.addAttribute("hospitalizationNoteResourceUrl", conf.getHospitalizationNoteResourceUrl());
		return "medrecord/medRecordMarkImagePagination.simple";
	}
	
	
	@RequestMapping("/paginationMedrecordShow")
	public String paginationMedrecordShow(String firstGuid, Model model){
		List<Map<String,Object>> hospitalizationNotes = medRecordService.getHospitalizationNoteByFirstGuid(firstGuid);
		model.addAttribute("hospitalizationNotes", hospitalizationNotes);
		List<Map<String,Object>> scanFiles = scanFileService.getPaginationScanFilesByFirstGuid(firstGuid);
		model.addAttribute("scanFiles", scanFiles);
		List<MrPageType> mrPageTypes = mrPageTypeService.getMrPageTypes();
		List<Map<String,Object>> mrPageTypesOfPagination = mrPageTypeService.getMrPageTypesOfPaginationCountByFirstGuid(firstGuid);
		model.addAttribute("mrPageTypes", mrPageTypes);
		Map<Integer, Map<String,Object>> mrPageTypesOfPaginationMap = new HashMap<Integer, Map<String,Object>>();
		for (Map<String, Object> mrPageTypeOfPagination : mrPageTypesOfPagination) {
			mrPageTypesOfPaginationMap.put((Integer)mrPageTypeOfPagination.get("mr_page_type"), mrPageTypeOfPagination);
		}
		model.addAttribute("mrPageTypesOfPaginationMap", mrPageTypesOfPaginationMap);
		model.addAttribute("hospitalizationNoteResourceUrl", conf.getHospitalizationNoteResourceUrl());
		return "medrecord/medRecordPaginationShow.simple";
	}
	
	@PostMapping("/paginationMedrecordImage")
	@ResponseBody
	public Result paginationMedrecordImage(String firstGuid,String fileHash,Integer mrPageTypeId,Integer oldMrPageTypeId){
		//设置为已经编页
		int result = medRecordService.paginationMedrecordImage(firstGuid, fileHash, mrPageTypeId);
		
		if(result == 0){
			return new Result(false, "病案图片编页失败", null);
		}
		
		List<Integer> mrPageTypes = new ArrayList<Integer>();
		
		if(oldMrPageTypeId != null){
			mrPageTypes.add(oldMrPageTypeId);
		}
		
		mrPageTypes.add(mrPageTypeId);
		
		//编页标签的编页数量
		List<Map<String, Object>> resultMap = mrPageTypeService.getMrPageTypesOfPaginationCountByFirstGuidAndMrPageTypes(firstGuid, mrPageTypes);
		Map<Integer, Map<String,Object>> mrPageTypesOfPaginationMap = new HashMap<Integer, Map<String,Object>>();
		
		for (Map<String, Object> mrPageTypeOfPagination : resultMap) {
			mrPageTypesOfPaginationMap.put((Integer)mrPageTypeOfPagination.get("mr_page_type"), mrPageTypeOfPagination);
		}
		//mrPageTypesOfPaginationMap.put("fileHash", fileHash);
		
		return new Result(true, fileHash, mrPageTypesOfPaginationMap);
	}
	
	@ResponseBody
	@PostMapping("/batchPaginationMedrecordImage")
	public Result batchPaginationMedrecordImage(String medicalResourceJsonStr, Integer mrPageTypeId, String firstGuid) {
		Result result = null;
		
		try {
			Set<Integer> mrPageTypesSet = medRecordService.batchPaginationMedrecordImage(medicalResourceJsonStr, mrPageTypeId, firstGuid);
			List<Integer> mrPageTypes = new ArrayList<Integer>();
			
			for (Integer pagetTypeId : mrPageTypesSet) {
				mrPageTypes.add(pagetTypeId);
			}
			
			//编页标签的编页数量
			List<Map<String, Object>> resultMap = mrPageTypeService.getMrPageTypesOfPaginationCountByFirstGuidAndMrPageTypes(firstGuid, mrPageTypes);
			Map<Integer, Map<String,Object>> mrPageTypesOfPaginationMap = new HashMap<Integer, Map<String,Object>>();
			
			for (Map<String, Object> mrPageTypeOfPagination : resultMap) {
				mrPageTypesOfPaginationMap.put((Integer)mrPageTypeOfPagination.get("mr_page_type"), mrPageTypeOfPagination);
			}
			
			result = new Result(true, "添加成功!", mrPageTypesOfPaginationMap);
		} catch (Exception e) {
			result = new Result(false, "系统异常" + ExceptionUtil.getStackTrace(e));
		}
		
		return result;
		
	}
	
	
	
	@ResponseBody
	@RequestMapping("/updateMedResource")
	public String updateMedResource(String firstGuid,String fileHash,Integer status){
		try {
			medRecordService.updateMedResource(firstGuid, fileHash, status);
			return "success";
		} catch (Exception e) {
			e.printStackTrace();
			return "false";
		}
		
	}
	
	
	@RequestMapping("/queryMedrecordHomePage")
	public String queryMedrecordHomePage(MedRecordQuery params,Model model){
		LeftMenuPojo leftMenu = LeftMenuPojo.GetLeftMenu("query_module");
		String leftMenuJson = JsonUtils.objectToJson(leftMenu);
		List<Map<String,Object>> hospitalizationNotes = new ArrayList<Map<String,Object>>();
		if (!params.IsPropertyEmpty()) {
			hospitalizationNotes = medRecordService.getHospitalizationNoteOfHomePageList(params);
			int count = medRecordService.getHospitalizationNoteOfHomePageCount(params);
			params.setTotalCounts(count);
		}
		
		
		
//		List<Map<String,Object>> hospitalizationNotes = medRecordService.getHospitalizationNoteList(params);
//		int count = medRecordService.getHospitalizationNoteCount(params);
//		params.setTotalCounts(count);
		
		model.addAttribute("hospitalizationNotes", hospitalizationNotes);
		model.addAttribute("leftMenuJson", leftMenuJson);
		model.addAttribute("medRecordQuery", params);
		return "query/medicalHomePageQuery.page";
	}
	
	
	
	
	@RequestMapping("/printSetting")
	public String printSetting(MedRecordQuery params,Model model){
		LeftMenuPojo leftMenu = LeftMenuPojo.GetLeftMenu("query_module");
		String leftMenuJson = JsonUtils.objectToJson(leftMenu);
		List<Map<String,Object>> printTypeList = baseInfoService.getPrintTypeList();
		
		model.addAttribute("leftMenuJson", leftMenuJson);
		model.addAttribute("printTypeList", printTypeList);
		return "query/printSetting.page";
	}
	
	@ResponseBody
	@RequestMapping("/getPrintData")
	public Result getPrintData(Integer mrPrintTypeId){
		Result result = null;
		try {
			List<Map<String,Object>> printData = baseInfoService.getPrintData(mrPrintTypeId);
			result = new Result(true,"查询成功!",printData);
		} catch (Exception e) {
			e.printStackTrace();
			result = new Result(false,"查询失败!");
		}
		return result;
	}
	
	@ResponseBody
	@RequestMapping("/addPageTypes")
	public Result addPageTypes(String pageTypeIds,Integer mrPrintTypeId){
		Result result = null;
		try {
			//List<Map<String,Object>> printData = baseInfoService.getPrintData(mrPrintTypeId);
			baseInfoService.addPageTypes(pageTypeIds,mrPrintTypeId);
			result = new Result(true);
		} catch (Exception e) {
			e.printStackTrace();
			result = new Result(false);
		}
		return result;
	}
	
	
	
	
	
	
	
	
	
	
	@RequestMapping("/medrecordHomePageManage")
	public String medrecordHomePageManage(String firstGuid, Model model){
		List<Map<String,Object>> hospitalizationNotes = medRecordService.getHospitalizationNoteBasicByFirstGuid(firstGuid);
		if(hospitalizationNotes.size() > 0){
			model.addAttribute("hospitalizationNote", hospitalizationNotes.get(0));
		}
		Map<String, List<Map<String,Object>>> basicInfoMap = basicInfoService.getBasicInfos();
		basicInfoMap.put("offices", basicInfoService.getMedicalOfficesByHospitalId(1));
		model.addAttribute("basicInfos", basicInfoMap);
		String filePath = conf.getHospitalizationNoteResourcePath();
		String fileName = firstGuid + ".txt";
		HospitalizationNoteBasic noteBasic = null;
		try {
			//Map<String, String> jsonMap = readLineFile(filePath,fileName);
			
			//根据firstGuid查询住院基本信息
			String hosBasicJson=hospNoteBasicJsonService.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(firstGuid));
			Map<String, Object> jsonMap =this.getHospBasicJson(hosBasicJson);
			 if(jsonMap.get("hospitalizationNoteBasic")!=null){
			        noteBasic= JsonUtils.jsonToPojo(JsonUtils.objectToJson(jsonMap.get("hospitalizationNoteBasic")),HospitalizationNoteBasic.class) ;
		      }
			addMedrecordHomePageInfo(model,jsonMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute("noteBasic", noteBasic);
		return "medrecord/medRecordHomePageManage.simple";
	}
	
	@RequestMapping(value ="/medrecordHomePageManageOfCureInfo",method=RequestMethod.POST)
	public String medrecordHomePageManageOfCureInfo(HospitalizationCureInfo hospitalizationCureInfo, Model model){
		String filePath = conf.getHospitalizationNoteResourcePath();
		String fileName = hospitalizationCureInfo.getFirstGuid() + ".txt";
		try {
			//Map<String, String> jsonMap = readLineFile(filePath,fileName);
			//根据firstGuid查询住院基本信息
			String hosBasicJson=hospNoteBasicJsonService.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(hospitalizationCureInfo.getFirstGuid()));
			Map<String, Object> jsonMap =this.getHospBasicJson(hosBasicJson);
			jsonMap.put("hospitalizationCureInfo", hospitalizationCureInfo);
			
			if(jsonMap!=null && jsonMap.size()>0){
				hospNoteBasicJsonService.updateHospBasicJsonByFirstGuid(hospitalizationCureInfo.getFirstGuid(), JsonUtils.objectToJson(jsonMap));
			}else{
				jsonMap.put("firstGuid", hospitalizationCureInfo.getFirstGuid());
				hospNoteBasicJsonService.addHospNoteBasicJson(JsonUtils.objectToJson(jsonMap));
			}
			String jsonStr = JsonUtils.objectToJson(jsonMap);
			addMedrecordHomePageInfo(model,jsonMap);
			CreateFileUtil.createFile(jsonStr, filePath, fileName);
		} catch (IOException e) {
			e.printStackTrace();
		}
		List<Map<String,Object>> hospitalizationNotes = medRecordService.getHospitalizationNoteBasicByFirstGuid(hospitalizationCureInfo.getFirstGuid());
		if(hospitalizationNotes.size() > 0){
			model.addAttribute("hospitalizationNote", hospitalizationNotes.get(0));
		}
		Map<String, List<Map<String,Object>>> basicInfoMap = basicInfoService.getBasicInfos();
		basicInfoMap.put("offices", basicInfoService.getMedicalOfficesByHospitalId(1));
		model.addAttribute("basicInfos", basicInfoMap);
		return "medrecord/medRecordHomePageManage.simple";
	}
	
	@RequestMapping(value ="/medrecordHomePageManageOfBasic",method=RequestMethod.POST)
	public String medrecordHomePageManageOfBasic(HospitalizationNoteBasic noteBasic, Model model){
		/*Map<String, String> jsonMap = new HashMap<String, String>();
		jsonMap.put("hospitalizationNoteBasic", JsonUtils.objectToJson(noteBasic));
		String jsonStr = JsonUtils.objectToJson(jsonMap);
		Map<String, String> b = JsonUtils.jsonToPojo(jsonStr, Map.class);
		HospitalizationNoteBasic b1= JsonUtils.jsonToPojo((String)b.get("hospitalizationNoteBasic"), HospitalizationNoteBasic.class);;*/
		
		medRecordService.updateHospitalizationNoteBasic(noteBasic);
		
		String filePath = conf.getHospitalizationNoteResourcePath();
		String fileName = noteBasic.getFirstGuid() + ".txt";
		try {
			
			//-----------------------------------------------------------
/*			Map<String, String> jsonMap = readLineFile(filePath,fileName);
			jsonMap.put("hospitalizationNoteBasic", JsonUtils.objectToJson(noteBasic));
			String jsonStr = JsonUtils.objectToJson(jsonMap);
			hospNoteBasicJsonService.addHospNoteBasicJson(jsonStr);
			addMedrecordHomePageInfo(model,jsonMap);
			CreateFileUtil.createFile(jsonStr, filePath, fileName);*/
			//-----------------------------------------------------------
			
			//查询是否已存在一次住院信息
			String jsonStr =null;
			//根据firstGuid查询住院基本信息
			String hosBasicJson=hospNoteBasicJsonService.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(noteBasic.getFirstGuid()));
			Map<String, Object> jsonMap =this.getHospBasicJson(hosBasicJson);
			if(jsonMap!=null && jsonMap.size()>0){
				
				jsonMap.put("hospitalizationNoteBasic", noteBasic);
				jsonStr = JsonUtils.objectToJson(jsonMap);
				hospNoteBasicJsonService.updateHospBasicJsonByFirstGuid(noteBasic.getFirstGuid(), jsonStr);
			}else{
				jsonMap.put("hospitalizationNoteBasic", noteBasic);
				jsonMap.put("firstGuid", noteBasic.getFirstGuid());
				jsonStr = JsonUtils.objectToJson(jsonMap);
				hospNoteBasicJsonService.addHospNoteBasicJson(jsonStr);
			}
			addMedrecordHomePageInfo(model,jsonMap);
			CreateFileUtil.createFile(jsonStr, filePath, fileName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		List<Map<String,Object>> hospitalizationNotes = medRecordService.getHospitalizationNoteBasicByFirstGuid(noteBasic.getFirstGuid());
		if(hospitalizationNotes.size() > 0){
			model.addAttribute("hospitalizationNote", hospitalizationNotes.get(0));
		}
		Map<String, List<Map<String,Object>>> basicInfoMap = basicInfoService.getBasicInfos();
		basicInfoMap.put("offices", basicInfoService.getMedicalOfficesByHospitalId(1));
		model.addAttribute("basicInfos", basicInfoMap);
		return "medrecord/medRecordHomePageManage.simple";
	}
	
	@RequestMapping(value ="/medrecordHomePageManageOfDiagnosisInfo",method=RequestMethod.POST)
	public String medrecordHomePageManageOfDiagnosisInfo(HospitalizationDiagnosisInfo hospitalizationDiagnosisInfo, Model model){
		String filePath = conf.getHospitalizationNoteResourcePath();
		String fileName = hospitalizationDiagnosisInfo.getFirstGuid() + ".txt";
		try {
			
			
			//Map<String, String> jsonMap = readLineFile(filePath,fileName);
			List<HospitalizationDiagnosis> hospitalizationDiagnosisList = hospitalizationDiagnosisInfo.getHospitalizationDiagnosis();
			List<HospitalizationDiagnosis> removeDiagnosisList = new ArrayList<HospitalizationDiagnosis>();
			for(HospitalizationDiagnosis diagnosis:hospitalizationDiagnosisList){
				if(diagnosis.getDiagnoseTypeId()==null || diagnosis.getDiseaseCode()==null || diagnosis.getInHospitalDiseaseStateId()==null){
					removeDiagnosisList.add(diagnosis);
				}
			}
			//删除无效数据
			if(!removeDiagnosisList.isEmpty()){
				hospitalizationDiagnosisList.removeAll(removeDiagnosisList);
			}
			
			//----------------------------保存数据库json   start---------------------------------------
			//根据firstGuid获取住院json数据
			String hosBasicJson=hospNoteBasicJsonService.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(hospitalizationDiagnosisInfo.getFirstGuid()));
			Map<String,Object> jsonMap=this.getHospBasicJson(hosBasicJson);
			if(jsonMap!=null && jsonMap.size()>0){
				if(!hospitalizationDiagnosisList.isEmpty()){
					jsonMap.put("hospitalizationDiagnosisInfo", hospitalizationDiagnosisInfo);
					
				}else{
					jsonMap.remove("hospitalizationDiagnosisInfo");
				}
				hospNoteBasicJsonService.updateHospBasicJsonByFirstGuid(hospitalizationDiagnosisInfo.getFirstGuid(), JsonUtils.objectToJson(jsonMap));				
			}else{
				
				if(!hospitalizationDiagnosisList.isEmpty()){
					jsonMap.put("hospitalizationDiagnosisInfo", hospitalizationDiagnosisInfo);
					jsonMap.put("firstGuid", hospitalizationDiagnosisInfo.getFirstGuid());
					hospNoteBasicJsonService.addHospNoteBasicJson(JsonUtils.objectToJson(jsonMap));
				}
			}
			
			//----------------------------保存数据库json   end---------------------------------------
			//----------------------保存本地文本文件-----------------------------------------------	
			String jsonStr = JsonUtils.objectToJson(jsonMap);
			CreateFileUtil.createFile(jsonStr, filePath, fileName);
			addMedrecordHomePageInfo(model,jsonMap);
			//---------------------------------------------------------------------
		} catch (Exception e) {
			e.printStackTrace();
		}
		List<Map<String,Object>> hospitalizationNotes = medRecordService.getHospitalizationNoteBasicByFirstGuid(hospitalizationDiagnosisInfo.getFirstGuid());
		if(hospitalizationNotes.size() > 0){
			model.addAttribute("hospitalizationNote", hospitalizationNotes.get(0));
		}
		Map<String, List<Map<String,Object>>> basicInfoMap = basicInfoService.getBasicInfos();
		basicInfoMap.put("offices", basicInfoService.getMedicalOfficesByHospitalId(1));
		model.addAttribute("basicInfos", basicInfoMap);
		return "medrecord/medRecordHomePageManage.simple";
	}
	
	
	@RequestMapping(value ="/medrecordHomePageManageOfBloodTransfusionInfo",method=RequestMethod.POST)
	public String medrecordHomePageManageOfBloodTransfusionInfo(BloodTransfusionInfo bloodTransfusionInfo, Model model){
		String filePath = conf.getHospitalizationNoteResourcePath();
		String fileName = bloodTransfusionInfo.getFirstGuid() + ".txt";
		try {
			//Map<String, String> jsonMap = readLineFile(filePath,fileName);
			
			List<BloodTransfusion> bloodTransfusions = bloodTransfusionInfo.getBloodTransfusions();
			List<BloodTransfusion> removeBloodTransfusions = new ArrayList<BloodTransfusion>();
			for(BloodTransfusion bloodTransfusion:bloodTransfusions){
				if(bloodTransfusion.getBloodTypeId()==null || bloodTransfusion.getBloodTransfusionDate()==null){
					removeBloodTransfusions.add(bloodTransfusion);
				}
			}
			if(!removeBloodTransfusions.isEmpty()){
				bloodTransfusions.removeAll(removeBloodTransfusions);
			}
			
			
			//根据firstGuid获取住院json数据
			String hosBasicJson=hospNoteBasicJsonService.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(bloodTransfusionInfo.getFirstGuid()));
			Map<String,Object> jsonMap=this.getHospBasicJson(hosBasicJson);
			
			
			//数据存在
			if(jsonMap!=null && jsonMap.size()>0){
				if(!bloodTransfusions.isEmpty()){
					jsonMap.put("bloodTransfusionInfo", bloodTransfusionInfo);
				}else{
					jsonMap.remove("bloodTransfusionInfo");	
				}
				hospNoteBasicJsonService.updateHospBasicJsonByFirstGuid(bloodTransfusionInfo.getFirstGuid(), JsonUtils.objectToJson(jsonMap));				
			//数据不存在
			}else{
				if(!bloodTransfusions.isEmpty()){
					jsonMap.put("bloodTransfusionInfo", bloodTransfusionInfo);
					jsonMap.put("firstGuid", bloodTransfusionInfo.getFirstGuid());
					hospNoteBasicJsonService.addHospNoteBasicJson(JsonUtils.objectToJson(jsonMap));
				}
			}
			
			String jsonStr = JsonUtils.objectToJson(jsonMap);
			CreateFileUtil.createFile(jsonStr, filePath, fileName);
			addMedrecordHomePageInfo(model,jsonMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		List<Map<String,Object>> hospitalizationNotes = medRecordService.getHospitalizationNoteBasicByFirstGuid(bloodTransfusionInfo.getFirstGuid());
		if(hospitalizationNotes.size() > 0){
			model.addAttribute("hospitalizationNote", hospitalizationNotes.get(0));
		}
		Map<String, List<Map<String,Object>>> basicInfoMap = basicInfoService.getBasicInfos();
		basicInfoMap.put("offices", basicInfoService.getMedicalOfficesByHospitalId(1));
		model.addAttribute("basicInfos", basicInfoMap);
		return "medrecord/medRecordHomePageManage.simple";
	}
	
	
	@RequestMapping(value ="/medrecordHomePageManageOfOperationInfo",method=RequestMethod.POST)
	public String medrecordHomePageManageOfOperationInfo(HospitalizationOperationInfo hospitalizationOperationInfo,Model model){
		String filePath = conf.getHospitalizationNoteResourcePath();
		String fileName = hospitalizationOperationInfo.getFirstGuid() + ".txt";
		
		try {
			//Map<String, String> jsonMap = readLineFile(filePath,fileName);
			//根据firstGuid获取住院json数据
			String hosBasicJson=hospNoteBasicJsonService.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(hospitalizationOperationInfo.getFirstGuid()));
			Map<String,Object> jsonMap=this.getHospBasicJson(hosBasicJson);
			if(hospitalizationOperationInfo.getPeriOperationPeriodStartDate()!=null && hospitalizationOperationInfo.getPeriOperationPeriodEndDate()!=null){
				List<HospitalizationOperation> removeOperations = new ArrayList<HospitalizationOperation>();
				List<HospitalizationOperation> operations = hospitalizationOperationInfo.getOperations();
				for(HospitalizationOperation hope:operations){
					if(hope.getOperationStartDate()==null || hope.getOperationEndDate()==null || hope.getOperationCode()==null){
						removeOperations.add(hope);
					}
				}
				if(!removeOperations.isEmpty()){
					operations.removeAll(removeOperations);
				}
				
				if(jsonMap!=null && jsonMap.size()>0){
					
					if(!operations.isEmpty()){
						jsonMap.put("operationInfo", hospitalizationOperationInfo);
						
					}else{
						jsonMap.remove("operationInfo");
					}
					hospNoteBasicJsonService.updateHospBasicJsonByFirstGuid(hospitalizationOperationInfo.getFirstGuid(), JsonUtils.objectToJson(jsonMap));				
				}else{
					if(!operations.isEmpty()){
						jsonMap.put("firstGuid", hospitalizationOperationInfo.getFirstGuid());
						jsonMap.put("operationInfo", hospitalizationOperationInfo);
						
					}
					hospNoteBasicJsonService.addHospNoteBasicJson(JsonUtils.objectToJson(jsonMap));
				}
				
				
			}
			String jsonStr = JsonUtils.objectToJson(jsonMap);
			CreateFileUtil.createFile(jsonStr, filePath, fileName);
			addMedrecordHomePageInfo(model,jsonMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		List<Map<String,Object>> hospitalizationNotes = medRecordService.getHospitalizationNoteBasicByFirstGuid(hospitalizationOperationInfo.getFirstGuid());
		if(hospitalizationNotes.size() > 0){
			model.addAttribute("hospitalizationNote", hospitalizationNotes.get(0));
		}
		Map<String, List<Map<String,Object>>> basicInfoMap = basicInfoService.getBasicInfos();
		basicInfoMap.put("offices", basicInfoService.getMedicalOfficesByHospitalId(1));
		model.addAttribute("basicInfos", basicInfoMap);
		return "medrecord/medRecordHomePageManage.simple";
	}
	/**
	 * 
	 * 转科记录
	 * @param hospitalizationOperationInfo
	 * @param model
	 * @return
	 */
	@RequestMapping(value ="/medrecordHomePageManageOfChangeOfficeInfo",method=RequestMethod.POST)
	public String medrecordHomePageManageOfChangeOfficeInfo(HospitalizationChangeOfficeInfo hospitalizationChangeOfficeInfo,Model model){
		try {
			String filePath = conf.getHospitalizationNoteResourcePath();
			String fileName = hospitalizationChangeOfficeInfo.getFirstGuid() + ".txt";
			//Map<String, String> jsonMap = readLineFile(filePath,fileName);
			
			String hosBasicJson=hospNoteBasicJsonService.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(hospitalizationChangeOfficeInfo.getFirstGuid()));
			Map<String,Object> jsonMap=this.getHospBasicJson(hosBasicJson);
			
			List<HospitalizationChangeOffice> hospitalizationChangeOffices = hospitalizationChangeOfficeInfo.getHospitalizationChangeOffices();
			List<HospitalizationChangeOffice> removeHospitalizationChangeOffices = new ArrayList<HospitalizationChangeOffice>();
			for(HospitalizationChangeOffice changeOffice:hospitalizationChangeOffices){
				if(changeOffice.getInOfficeId()==null && changeOffice.getChangeOfficeDate()==null){
					removeHospitalizationChangeOffices.add(changeOffice);
				}else if(changeOffice.getOutOfficeId()==null && changeOffice.getChangeOfficeDate()==null){
					removeHospitalizationChangeOffices.add(changeOffice);
				}
			}
			
			if(!removeHospitalizationChangeOffices.isEmpty()){
				hospitalizationChangeOffices.removeAll(removeHospitalizationChangeOffices);
			}
			
			if(jsonMap!=null && jsonMap.size()>0){
				if(!hospitalizationChangeOffices.isEmpty()){
					jsonMap.put("hospitalChangeOfficeInfo", hospitalizationChangeOfficeInfo);
				}else{
					jsonMap.remove("hospitalChangeOfficeInfo");
				}
				hospNoteBasicJsonService.updateHospBasicJsonByFirstGuid(hospitalizationChangeOfficeInfo.getFirstGuid(), JsonUtils.objectToJson(jsonMap));				
			}else{
				if(!hospitalizationChangeOffices.isEmpty()){
					jsonMap.put("hospitalChangeOfficeInfo", JsonUtils.objectToJson(hospitalizationChangeOfficeInfo));
					jsonMap.put("firstGuid", hospitalizationChangeOfficeInfo.getFirstGuid());
					hospNoteBasicJsonService.addHospNoteBasicJson(JsonUtils.objectToJson(jsonMap));
				}
			}
			
			String jsonStr = JsonUtils.objectToJson(jsonMap);
			CreateFileUtil.createFile(jsonStr, filePath, fileName);
			addMedrecordHomePageInfo(model,jsonMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		List<Map<String,Object>> hospitalizationNotes = medRecordService.getHospitalizationNoteBasicByFirstGuid(hospitalizationChangeOfficeInfo.getFirstGuid());
		if(hospitalizationNotes.size() > 0){
			model.addAttribute("hospitalizationNote", hospitalizationNotes.get(0));
		}
		Map<String, List<Map<String,Object>>> basicInfoMap = basicInfoService.getBasicInfos();
		basicInfoMap.put("offices", basicInfoService.getMedicalOfficesByHospitalId(1));
		model.addAttribute("basicInfos", basicInfoMap);
		return "medrecord/medRecordHomePageManage.simple";
	}
	
	
	/**
	 * 
	 * 产科记录
	 * @param hospitalizationOperationInfo
	 * @param model
	 * @return
	 */
	@RequestMapping(value ="/medrecordHomePageManageOfobstetricalRecordInfo",method=RequestMethod.POST)
	public String medrecordHomePageManageOfobstetricalRecordInfo(ObstetricalRecordInfo obstetricalRecordInfo,Model model){
		String firstGuid = obstetricalRecordInfo.getFirstGuid();
		try {
			String filePath = conf.getHospitalizationNoteResourcePath();
			String fileName = firstGuid + ".txt";
			//Map<String, String> jsonMap = readLineFile(filePath,fileName);
			
			String hosBasicJson=hospNoteBasicJsonService.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(obstetricalRecordInfo.getFirstGuid()));
			Map<String,Object> jsonMap=this.getHospBasicJson(hosBasicJson);
			
			List<ObstetricalRecord> obstetricalRecords = obstetricalRecordInfo.getObstetricalRecords();
			List<ObstetricalRecord> removeObstetricalRecords = new ArrayList<>();
			
			for(ObstetricalRecord bean:obstetricalRecords){
				if(bean.getGestationalWeeks()==null || bean.getFetusPositionId()==null || bean.getChildBirthId()==null
						|| bean.getSexId()==null || bean.getNeonateBornDate()==null || bean.getNeonateBornWeight()==null || bean.getNeonateBornHeight()==null) {
					removeObstetricalRecords.add(bean);
				}
	         }
			if(!removeObstetricalRecords.isEmpty()){
				obstetricalRecords.removeAll(removeObstetricalRecords);
			}
			
			
			if(jsonMap!=null && jsonMap.size()>0){
				
				if(!obstetricalRecords.isEmpty()){
					jsonMap.put("obstetricalRecordInfo", obstetricalRecordInfo);
				}else{
					jsonMap.remove("obstetricalRecordInfo");
				}
				hospNoteBasicJsonService.updateHospBasicJsonByFirstGuid(obstetricalRecordInfo.getFirstGuid(), JsonUtils.objectToJson(jsonMap));
				
			}else{
				if(!obstetricalRecords.isEmpty()){
					jsonMap.put("firstGuid", obstetricalRecordInfo.getFirstGuid());
					jsonMap.put("obstetricalRecordInfo", obstetricalRecordInfo);
				}
				hospNoteBasicJsonService.addHospNoteBasicJson(JsonUtils.objectToJson(jsonMap));
			}
			String jsonStr = JsonUtils.objectToJson(jsonMap);
			CreateFileUtil.createFile(jsonStr, filePath, fileName);
			addMedrecordHomePageInfo(model,jsonMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		List<Map<String,Object>> hospitalizationNotes = medRecordService.getHospitalizationNoteBasicByFirstGuid(firstGuid);
		if(hospitalizationNotes.size() > 0){
			model.addAttribute("hospitalizationNote", hospitalizationNotes.get(0));
		}
		Map<String, List<Map<String,Object>>> basicInfoMap = basicInfoService.getBasicInfos();
		basicInfoMap.put("offices", basicInfoService.getMedicalOfficesByHospitalId(1));
		model.addAttribute("basicInfos", basicInfoMap);
		return "medrecord/medRecordHomePageManage.simple";
	}
	
	/**
	 * 
	 * 医院感染
	 * @param hospitalInfectionInfo
	 * @param model
	 * @return
	 */
	@RequestMapping(value ="/medrecordHomePageManageOfHospitalInfectionInfo",method=RequestMethod.POST)
	public String medrecordHomePageManageOfHospitalInfectionInfo(HospitalInfectionInfo hospitalInfectionInfo,Model model){
		String firstGuid = hospitalInfectionInfo.getFirstGuid();
		try {
			String filePath = conf.getHospitalizationNoteResourcePath();
			String fileName = firstGuid + ".txt";
			//Map<String, String> jsonMap = readLineFile(filePath,fileName);
			String hosBasicJson=hospNoteBasicJsonService.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(hospitalInfectionInfo.getFirstGuid()));
			Map<String,Object> jsonMap=this.getHospBasicJson(hosBasicJson);
			
			List<HospitalInfection> hospitalInfects = hospitalInfectionInfo.getHospitalInfects();
			List<HospitalInfection> removeHospitalInfects = new ArrayList<>();
			
			for(HospitalInfection hospitalInfection:hospitalInfects){
				if(hospitalInfection.getReportDate()==null || hospitalInfection.getPathogenyId()==null || hospitalInfection.getPathogenyExemplarId()==null){
					removeHospitalInfects.add(hospitalInfection);
				}
			}
			
			if(!removeHospitalInfects.isEmpty()){
				hospitalInfects.removeAll(removeHospitalInfects);
			}
			
			if(jsonMap!=null && jsonMap.size()>0){
				
				if(!hospitalInfects.isEmpty()){
					jsonMap.put("hospitalInfectionInfo",hospitalInfectionInfo);
					
				}else{
					jsonMap.remove("hospitalInfectionInfo");
				}
				hospNoteBasicJsonService.updateHospBasicJsonByFirstGuid(hospitalInfectionInfo.getFirstGuid(), JsonUtils.objectToJson(jsonMap));
				
			}else{
				if(!hospitalInfects.isEmpty()){
					jsonMap.put("firstGuid", hospitalInfectionInfo.getFirstGuid());
					jsonMap.put("obstetricalRecordInfo", JsonUtils.objectToJson(hospitalInfectionInfo));
				}
				hospNoteBasicJsonService.addHospNoteBasicJson(JsonUtils.objectToJson(jsonMap));
			}
			
			
	
			String jsonStr = JsonUtils.objectToJson(jsonMap);
			CreateFileUtil.createFile(jsonStr, filePath, fileName);
			addMedrecordHomePageInfo(model,jsonMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		List<Map<String,Object>> hospitalizationNotes = medRecordService.getHospitalizationNoteBasicByFirstGuid(firstGuid);
		if(hospitalizationNotes.size() > 0){
			model.addAttribute("hospitalizationNote", hospitalizationNotes.get(0));
		}
		Map<String, List<Map<String,Object>>> basicInfoMap = basicInfoService.getBasicInfos();
		basicInfoMap.put("offices", basicInfoService.getMedicalOfficesByHospitalId(1));
		model.addAttribute("basicInfos", basicInfoMap);
		return "medrecord/medRecordHomePageManage.simple";
	}
	
	@RequestMapping(value ="/medrecordHomePageManageOfHospitalizationCost",method=RequestMethod.POST)
	public String medrecordHomePageManageOfHospitalizationCost(HospitalizationCost hospitalizationCost,Model model){
		String firstGuid = hospitalizationCost.getFirstGuid();
		try {
			String filePath = conf.getHospitalizationNoteResourcePath();
			String fileName = firstGuid + ".txt";
			//Map<String, String> jsonMap = readLineFile(filePath,fileName);
			String hosBasicJson=hospNoteBasicJsonService.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(hospitalizationCost.getFirstGuid()));
			Map<String,Object> jsonMap=this.getHospBasicJson(hosBasicJson);
			if(jsonMap!=null && jsonMap.size()>0){
				jsonMap.put("hospitalizationCost",hospitalizationCost);
				hospNoteBasicJsonService.updateHospBasicJsonByFirstGuid(hospitalizationCost.getFirstGuid(), JsonUtils.objectToJson(jsonMap));
			}else{
				jsonMap.put("firstGuid", hospitalizationCost.getFirstGuid());
				jsonMap.put("hospitalizationCost",hospitalizationCost);
				hospNoteBasicJsonService.addHospNoteBasicJson(JsonUtils.objectToJson(jsonMap));
			}
			String jsonStr = JsonUtils.objectToJson(jsonMap);
			CreateFileUtil.createFile(jsonStr, filePath, fileName);
			addMedrecordHomePageInfo(model,jsonMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "redirect:/medrecord/medrecordHomePageManage?firstGuid="+firstGuid;
	}
	
	/**
	 * 护理记录
	 * @param hospitalizationNurseRecordInfo
	 * @param model
	 * @return
	 */
	@RequestMapping(value ="/medrecordHomePageManageOfHospitalizationNurseRecord",method=RequestMethod.POST)
	public String medrecordHomePageManageOfHospitalizationNurseRecord(HospitalizationNurseRecordInfo hospitalizationNurseRecordInfo,Model model){
		String firstGuid = hospitalizationNurseRecordInfo.getFirstGuid();
		try {
			String filePath = conf.getHospitalizationNoteResourcePath();
			String fileName = firstGuid + ".txt";
			hospitalizationNurseRecordInfo.clearEmptyNurseRecord();
			//Map<String, String> jsonMap = readLineFile(filePath,fileName);
			String hosBasicJson=hospNoteBasicJsonService.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(hospitalizationNurseRecordInfo.getFirstGuid()));
			Map<String,Object> jsonMap=this.getHospBasicJson(hosBasicJson);
			if(jsonMap!=null && jsonMap.size()>0){
				jsonMap.put("hospitalizationNurseRecordInfo",hospitalizationNurseRecordInfo);
				hospNoteBasicJsonService.updateHospBasicJsonByFirstGuid(hospitalizationNurseRecordInfo.getFirstGuid(), JsonUtils.objectToJson(jsonMap));
			}else{
				jsonMap.put("firstGuid", hospitalizationNurseRecordInfo.getFirstGuid());
				jsonMap.put("hospitalizationNurseRecordInfo",hospitalizationNurseRecordInfo);
				hospNoteBasicJsonService.addHospNoteBasicJson(JsonUtils.objectToJson(jsonMap));
			}
			String jsonStr = JsonUtils.objectToJson(jsonMap);
			CreateFileUtil.createFile(jsonStr, filePath, fileName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "redirect:/medrecord/medrecordHomePageManage?firstGuid="+firstGuid;
	}
	
	/**
	 * 重症监护
	 * @param hospitalizationIntensiveCareInfo
	 * @param model
	 * @return
	 */
	@RequestMapping(value ="/medrecordHomePageManageOfIntensiveCareRecordInfo",method=RequestMethod.POST)
	public String medrecordHomePageManageOfIntensiveCareRecordInfo(HospitalizationIntensiveCareInfo hospitalizationIntensiveCareInfo,Model model){
		String firstGuid = hospitalizationIntensiveCareInfo.getFirstGuid();
		try {
			String filePath = conf.getHospitalizationNoteResourcePath();
			String fileName = firstGuid + ".txt";
			//Map<String, String> jsonMap = readLineFile(filePath,fileName);
			String hosBasicJson=hospNoteBasicJsonService.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(hospitalizationIntensiveCareInfo.getFirstGuid()));
			Map<String,Object> jsonMap=this.getHospBasicJson(hosBasicJson);
			if(jsonMap!=null && jsonMap.size()>0){
				jsonMap.put("hospitalizationIntensiveCareInfo",hospitalizationIntensiveCareInfo);
				hospNoteBasicJsonService.updateHospBasicJsonByFirstGuid(hospitalizationIntensiveCareInfo.getFirstGuid(), JsonUtils.objectToJson(jsonMap));
			}else{
				jsonMap.put("firstGuid", hospitalizationIntensiveCareInfo.getFirstGuid());
				jsonMap.put("hospitalizationIntensiveCareInfo",hospitalizationIntensiveCareInfo);
				hospNoteBasicJsonService.addHospNoteBasicJson(JsonUtils.objectToJson(jsonMap));
			}
			String jsonStr = JsonUtils.objectToJson(jsonMap);
			CreateFileUtil.createFile(jsonStr, filePath, fileName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "redirect:/medrecord/medrecordHomePageManage?firstGuid="+firstGuid;
	}
	
	
	/**
	 * 药物过敏
	 * @param drugAllergyInfo
	 * @param model
	 * @return
	 */
	@RequestMapping(value ="/medrecordHomePageManageOfDrugAllergyInfo",method=RequestMethod.POST)
	public String medrecordHomePageManageOfDrugAllergyInfo(HospitalizationDrugAllergyInfo drugAllergyInfo,Model model){
		String firstGuid = drugAllergyInfo.getFirstGuid();
		try {
			String filePath = conf.getHospitalizationNoteResourcePath();
			String fileName = firstGuid + ".txt";
			//Map<String, String> jsonMap = readLineFile(filePath,fileName);
			String hosBasicJson=hospNoteBasicJsonService.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(drugAllergyInfo.getFirstGuid()));
			Map<String,Object> jsonMap=this.getHospBasicJson(hosBasicJson);
			if(jsonMap!=null && jsonMap.size()>0){
				jsonMap.put("hospitalizationDrugAllergyInfo",drugAllergyInfo);
				hospNoteBasicJsonService.updateHospBasicJsonByFirstGuid(drugAllergyInfo.getFirstGuid(), JsonUtils.objectToJson(jsonMap));
			}else{
				jsonMap.put("firstGuid", drugAllergyInfo.getFirstGuid());
				jsonMap.put("hospitalizationDrugAllergyInfo",drugAllergyInfo);
				hospNoteBasicJsonService.addHospNoteBasicJson(JsonUtils.objectToJson(jsonMap));
			}
			String jsonStr = JsonUtils.objectToJson(jsonMap);
			CreateFileUtil.createFile(jsonStr, filePath, fileName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "redirect:/medrecord/medrecordHomePageManage?firstGuid="+firstGuid;
	}
	
	
	@RequestMapping(value ="/medrecordHomePageManageOfPressureSoreInfo",method=RequestMethod.POST)
	public String medrecordHomePageManageOfPressureSoreInfo(HospitalizationPressureSoreInfo pressureSoreInfo, Model model){
		String firstGuid = pressureSoreInfo.getFirstGuid();
		
		try {
			String filePath = conf.getHospitalizationNoteResourcePath();
			String fileName = firstGuid + ".txt";
			//Map<String, String> jsonMap = readLineFile(filePath,fileName);
			String hosBasicJson = hospNoteBasicJsonService.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(pressureSoreInfo.getFirstGuid()));
			Map<String,Object> jsonMap = this.getHospBasicJson(hosBasicJson);
			
			if (jsonMap != null && jsonMap.size()>0) {
				jsonMap.put("hospitalizationPressureSoreInfo", pressureSoreInfo);
				hospNoteBasicJsonService.updateHospBasicJsonByFirstGuid(pressureSoreInfo.getFirstGuid(), JsonUtils.objectToJson(jsonMap));
			} else {
				jsonMap.put("firstGuid", pressureSoreInfo.getFirstGuid());
				jsonMap.put("hospitalizationPressureSoreInfo",pressureSoreInfo);
				hospNoteBasicJsonService.addHospNoteBasicJson(JsonUtils.objectToJson(jsonMap));
			}
			String jsonStr = JsonUtils.objectToJson(jsonMap);
			CreateFileUtil.createFile(jsonStr, filePath, fileName);
		} catch (Exception e) {
			log.error("");
			e.printStackTrace();
		}
		
		return "redirect:/medrecord/medrecordHomePageManage?firstGuid="+firstGuid;
	}
	
	/**
	 * 读取数据库中存储的json信息转换为map
	 * @param json
	 * @return
	 */
	public Map<String,Object> getHospBasicJson(String json){
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			if (StringUtil.isNotEmpty(json)) {
				jsonMap = JsonUtils.jsonToPojo(json, Map.class);
			}
		} catch (Exception e) {
			log.error("getHospBasicJson异常"+ExceptionUtil.getStackTrace(e));
			e.printStackTrace();
		}
		
		return jsonMap;
		
	}
	
	/**
	 * 读取文件中数据
	 * @param filePath
	 * @param fileName
	 * @return
	 */
	public Map<String, String> readLineFile(String filePath, String fileName){
		Map<String, String> jsonMap = new HashMap<String, String>();
		
		try {
			File destFile = new File(filePath,fileName);
			String jsonStr = null;
			if(destFile.exists()){
				 FileReader fr = new FileReader(destFile);
			        BufferedReader br = new BufferedReader(fr);
			        jsonStr = br.readLine();
			        jsonMap = JsonUtils.jsonToPojo(jsonStr, Map.class);
			       
			}
		} catch (IOException e) {
			log.error("读取文件中数据异常:"+ExceptionUtil.getStackTrace(e));
			e.printStackTrace();
		}
		
		return jsonMap;
	}
	
	
	private void addMedrecordHomePageInfo(Model model,Map<String, Object> jsonMap){
		if (jsonMap.get("hospitalizationNoteBasic") != null) {
			model.addAttribute("noteBasic",JsonUtils.jsonToPojo(JsonUtils.objectToJson(jsonMap.get("hospitalizationNoteBasic")),
					HospitalizationNoteBasic.class));
		}
		
		if (jsonMap.get("hospitalizationCureInfo") != null) {
			model.addAttribute("hospitalizationCureInfo", JsonUtils.jsonToPojo(JsonUtils.objectToJson(jsonMap.get("hospitalizationCureInfo")),
					HospitalizationCureInfo.class));
		}
		
		//yimr
		if (jsonMap.get("hospitalizationDiagnosisInfo") == null) {
			HospitalizationDiagnosisInfo hospitalizationDiagnosisInfo = new HospitalizationDiagnosisInfo();
			jsonMap.put("hospitalizationDiagnosisInfo", hospitalizationDiagnosisInfo);
		}
		
		model.addAttribute("hospitalizationDiagnosisInfo",JsonUtils.jsonToPojo(JsonUtils.objectToJson(jsonMap.get("hospitalizationDiagnosisInfo")),HospitalizationDiagnosisInfo.class));

		if (jsonMap.get("operationInfo") == null) {
			HospitalizationOperationInfo hospitalizationOperationInfo = new HospitalizationOperationInfo();
			jsonMap.put("operationInfo", hospitalizationOperationInfo);
		}
		
		model.addAttribute("operationInfo",JsonUtils.jsonToPojo(JsonUtils.objectToJson(jsonMap.get("operationInfo")),
				HospitalizationOperationInfo.class));
		
		if (jsonMap.get("bloodTransfusionInfo") == null) { 
			BloodTransfusionInfo bloodTransfusionInfo = new BloodTransfusionInfo();
			jsonMap.put("bloodTransfusionInfo", bloodTransfusionInfo);
		}
		
		model.addAttribute("bloodTransfusionInfo",JsonUtils.jsonToPojo(JsonUtils.objectToJson(jsonMap.get("bloodTransfusionInfo")),BloodTransfusionInfo.class));
		
		if (jsonMap.get("hospitalChangeOfficeInfo") == null) {
			HospitalizationChangeOfficeInfo changeOfficeInfo = new HospitalizationChangeOfficeInfo();
			jsonMap.put("hospitalChangeOfficeInfo", changeOfficeInfo);
		}
		
		model.addAttribute("hospitalChangeOfficeInfo",JsonUtils.jsonToPojo(JsonUtils.objectToJson(jsonMap.get("hospitalChangeOfficeInfo")),HospitalizationChangeOfficeInfo.class));

		if (jsonMap.get("obstetricalRecordInfo") == null) {
			ObstetricalRecordInfo obstetricalRecordInfo = new ObstetricalRecordInfo();
			jsonMap.put("obstetricalRecordInfo", obstetricalRecordInfo);
		}
		
		model.addAttribute("obstetricalRecordInfo",JsonUtils.jsonToPojo(JsonUtils.objectToJson(jsonMap.get("obstetricalRecordInfo")),
				ObstetricalRecordInfo.class));
		
		if (jsonMap.get("hospitalInfectionInfo") ==null ) {
			HospitalInfectionInfo hospitalInfectionInfo = new HospitalInfectionInfo();
			jsonMap.put("hospitalInfectionInfo", hospitalInfectionInfo);
		}
		
		model.addAttribute("hospitalInfectionInfo",JsonUtils.jsonToPojo(JsonUtils.objectToJson(jsonMap.get("hospitalInfectionInfo")),HospitalInfectionInfo.class));
		
		if (jsonMap.get("hospitalizationCost") == null) {
			HospitalizationCost hospitalizationCost = new HospitalizationCost();
			jsonMap.put("hospitalizationCost", hospitalizationCost);
		} else {
			model.addAttribute("hospitalizationCost",JsonUtils.jsonToPojo(JsonUtils.objectToJson(jsonMap.get("hospitalizationCost")),
					HospitalizationCost.class));
		}
		
		if (jsonMap.get("hospitalizationNurseRecordInfo") ==null ) {
			HospitalizationNurseRecordInfo hospitalizationNurseRecordInfo = new HospitalizationNurseRecordInfo();
			jsonMap.put("hospitalizationNurseRecordInfo", hospitalizationNurseRecordInfo);
		} else {
			model.addAttribute("hospitalizationNurseRecordInfo",JsonUtils.jsonToPojo(JsonUtils.objectToJson(jsonMap.get("hospitalizationNurseRecordInfo")),
					HospitalizationNurseRecordInfo.class));
		}
		
		if (jsonMap.get("hospitalizationIntensiveCareInfo") ==null ) {
			HospitalizationIntensiveCareInfo hospitalizationIntensiveCareInfo = new HospitalizationIntensiveCareInfo();
			jsonMap.put("hospitalizationIntensiveCareInfo", hospitalizationIntensiveCareInfo);
		} else {
			model.addAttribute("hospitalizationIntensiveCareInfo",JsonUtils.jsonToPojo(JsonUtils.objectToJson(jsonMap.get("hospitalizationIntensiveCareInfo")),
					HospitalizationIntensiveCareInfo.class));
		}
		
		if (jsonMap.get("hospitalizationDrugAllergyInfo") ==null ) {
			HospitalizationDrugAllergyInfo hospitalizationDrugAllergyInfo = new HospitalizationDrugAllergyInfo();
			jsonMap.put("hospitalizationDrugAllergyInfo", hospitalizationDrugAllergyInfo);
		} else {
			model.addAttribute("hospitalizationDrugAllergyInfo",JsonUtils.jsonToPojo(JsonUtils.objectToJson(jsonMap.get("hospitalizationDrugAllergyInfo")),
					HospitalizationDrugAllergyInfo.class));
		}
		
		if (jsonMap.get("hospitalizationPressureSoreInfo")==null) {
			HospitalizationPressureSoreInfo hospitalizationPressureSoreInfo = new HospitalizationPressureSoreInfo();
			jsonMap.put("hospitalizationPressureSoreInfo", hospitalizationPressureSoreInfo);
		} else {
			model.addAttribute("hospitalizationPressureSoreInfo",JsonUtils.jsonToPojo(JsonUtils.objectToJson(jsonMap.get("hospitalizationPressureSoreInfo")),
					HospitalizationPressureSoreInfo.class));
		}
		
	}
	
	/**
	 * 获取住院病案首页数据用于打印
	 * 
	 * */
	@RequestMapping("/tobeHospitalizedHomePage")
	public String tobeHospitalizedHomePage(String firstGuid, Model model){
		List<Map<String,Object>> hospitalizationNotes = medRecordService.getHospitalizationNoteBasicByFirstGuid(firstGuid);
		
		if (hospitalizationNotes.size() > 0) {
			model.addAttribute("hospitalizationNote", hospitalizationNotes.get(0));
		}
		
		String json =hospNoteBasicJsonService.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(firstGuid));
		Map<String, Object> jsonMap = JsonUtils.jsonToPojo(json, Map.class);
		HospitalizationNoteBasic noteBasic = null;
		
		if(jsonMap.get("hospitalizationNoteBasic") != null) {
		        noteBasic= JsonUtils.jsonToPojo(JsonUtils.objectToJson(jsonMap.get("hospitalizationNoteBasic")), HospitalizationNoteBasic.class);
	      }
		
		addMedrecordHomePageInfo(model,jsonMap);
		
		BloodTransfusionInfo bloodInfo = JsonUtils.jsonToPojo(JsonUtils.objectToJson(jsonMap.get("bloodTransfusionInfo")),BloodTransfusionInfo.class);
		
		List<BloodTransfusion> bloodTransfusions = bloodInfo.getBloodTransfusions();
		int count = 0;
		int transfusionReactionCount = 0;
		BigDecimal redBloodCellVolumeCount = new BigDecimal(0);
		BigDecimal thrombocyteVolumeCount = new BigDecimal(0);
		BigDecimal plasmaVolumeCount = new BigDecimal(0);
		BigDecimal wholeBloodVolumeCount = new BigDecimal(0);
		BigDecimal autoBloodVolumeCount = new BigDecimal(0);
		StringBuffer otherInfo = new StringBuffer("");
		
		if (!bloodTransfusions.isEmpty()) {
			count = bloodTransfusions.size();
			
			for (BloodTransfusion bean:bloodTransfusions) {
				if (bean.getBloodTransfusionResponse() ==true ) {
					transfusionReactionCount = transfusionReactionCount+1;
				}
				
				if(bean.getRedBloodCellVolume() != null) {
					redBloodCellVolumeCount = redBloodCellVolumeCount.add(bean.getRedBloodCellVolume());
				}
				
				if(bean.getThrombocyteVolume() != null) {
					thrombocyteVolumeCount = thrombocyteVolumeCount.add(bean.getThrombocyteVolume());
				}
				
				if (bean.getPlasmaVolume() != null) {
					plasmaVolumeCount = plasmaVolumeCount.add(bean.getPlasmaVolume());
				}
				
				if (bean.getWholeBloodVolume() != null) {
					wholeBloodVolumeCount = wholeBloodVolumeCount.add(bean.getWholeBloodVolume());
				}
				
				if (bean.getAutoBloodVolume() != null) {
					autoBloodVolumeCount = autoBloodVolumeCount.add(bean.getAutoBloodVolume());
				}
				
				if (bean.getOtherInfo() != null && bean.getOtherInfo() != ""){
					otherInfo = otherInfo.append(bean.getOtherInfo()).append(",");
				}
			}
		}
		
		model.addAttribute("count",count) ;
		model.addAttribute("transfusionReactionCount",transfusionReactionCount);
		model.addAttribute("redBloodCellVolumeCount",redBloodCellVolumeCount) ;
		model.addAttribute("thrombocyteVolumeCount",thrombocyteVolumeCount) ;
		model.addAttribute("plasmaVolumeCount",plasmaVolumeCount) ;
		model.addAttribute("wholeBloodVolumeCount",wholeBloodVolumeCount) ;
		model.addAttribute("autoBloodVolumeCount",autoBloodVolumeCount) ;
		
		if (otherInfo.length()>0) {
			model.addAttribute("otherInfo",otherInfo.toString().substring(0,otherInfo.toString().lastIndexOf(",")));
		}
	
		model.addAttribute("noteBasic", noteBasic);
		return "print/beHospitalizedHomePage";
	}
	
	/**
	 * 补录数据页面
	 * @param params
	 * @param model
	 * @return
	 */
	@GetMapping("/newRedrecordForm")
	public String newRedrecordForm(HospitalizationNoteBasic hospitalNote, Model model){
		LeftMenuPojo leftMenu = LeftMenuPojo.GetLeftMenu("collection_module");
		model.addAttribute("basicInfo", basicInfoService.getSimpleBasicInfos());
		model.addAttribute("offices", basicInfoService.getMedicalOfficesByHospitalId(1));
		String leftMenuJson = JsonUtils.objectToJson(leftMenu);
		model.addAttribute("hospitalNote", hospitalNote);
		model.addAttribute("leftMenuJson", leftMenuJson);
		
		return "medrecord/medRecordNew.page";
	}
	
	/**
	 * 补录数据
	 * @param params
	 * @param model
	 * @return
	 */
	@PostMapping("/newRedrecord")
	@ResponseBody
	public Result newRedrecord(HospitalizationNoteBasic hospitalNote, Model model, HttpServletRequest request) {
		String currentUser = CookieUtils.getCookieValue(request, "userName");
		
		String mrId = hospitalNote.getMrId();
		if (StringUtils.isNotBlank(mrId)) {
			int length = mrId.length();
			if (length < 3) {
				return new Result(false, "ID号长度不能小于3");
			}
			
			//获取最后两位
			String str = mrId.substring(mrId.length()-2, mrId.length());
			if (!str.equals("#a")) {
				return new Result(false, "ID号最后两位必须是#a");
			}
			
		}
		
		Result result = medRecordService.addSimpleMedRecord(hospitalNote, currentUser);
		
//		if (result < 1) {
//			LeftMenuPojo leftMenu = LeftMenuPojo.GetLeftMenu("collection_module");
//			model.addAttribute("basicInfo", basicInfoService.getSimpleBasicInfos());
//			model.addAttribute("offices", basicInfoService.getMedicalOfficesByHospitalId(1));
//			String leftMenuJson = JsonUtils.objectToJson(leftMenu);
//			model.addAttribute("hospitalNote", hospitalNote);
//			model.addAttribute("leftMenuJson", leftMenuJson);
//			
//			return "medrecord/medRecordNew.page";
//		}
		
		return result;
		//return "redirect:/medrecord/unPigeonhole?mrId="+ hospitalNote.getMrId();
	}
	
	
	@GetMapping("/unPigeonhole")
	public String unPigeonhole(Model model){
		LeftMenuPojo leftMenu = LeftMenuPojo.GetLeftMenu("collection_module");
		String leftMenuJson = JsonUtils.objectToJson(leftMenu);
		model.addAttribute("leftMenuJson", leftMenuJson);
		return "medrecord/medDataFetchPage.page";
	}
	
	
	
	/**
	 * 未归病案
	 * @param params
	 * @param model
	 * @return
	 */
	@GetMapping("/medDataFetchPage")
	public String medDataFetchPage(MedRecordQuery params,Model model){
		/*List<Map<String,Object>> unBindList=medBindService.getUnBindList(params);
		int countSize=medBindService.getUnBindCount(params);
		model.addAttribute("unBindList", unBindList);
		model.addAttribute("unBindSize", countSize);*/
		LeftMenuPojo leftMenu = LeftMenuPojo.GetLeftMenu("collection_module");
		String leftMenuJson = JsonUtils.objectToJson(leftMenu);
		List<Map<String,Object>> medicalOffices = basicInfoService.getMedicalOfficesByHospitalId(1);
		model.addAttribute("basicInfo", basicInfoService.getSimpleBasicInfos());
		List<Map<String,Object>> hospitalNotes = new ArrayList<Map<String,Object>>();
		int count = 0;
		if (!params.IsPropertyEmpty()) {
			hospitalNotes = medRecordService.getUnPigeonhole(params);
			count = medRecordService.getUnPigeonholeCount(params);
		}
		
		
		params.setTotalCounts(count);
		
		model.addAttribute("hospitalNotesJson", JsonUtils.objectToJson(hospitalNotes));
		model.addAttribute("pageJson", JsonUtils.objectToJson(params));
		model.addAttribute("leftMenuJson", leftMenuJson);
		model.addAttribute("medRecordQuery", params);
		model.addAttribute("offices", medicalOffices);
		
		return "medrecord/unPigeonhole.page";
	}
	
	@GetMapping("/ajaxPigeonholed")
	@ResponseBody
	public Result ajaxPigeonholed(MedRecordQuery params, Model model, HttpServletResponse response){
		response.setHeader("Access-Control-Allow-Origin", "*");
		Result result=null;
		Map<String,Object> resultMap = new HashMap<String, Object>();
		List<Map<String,Object>> hospitalNotes = new ArrayList<Map<String,Object>>();
		
		if (!params.IsPropertyEmpty()) {
			hospitalNotes = medRecordService.getPigeonholed(params);
		}
		
		int count = medRecordService.getPigeonholedCount(params);
		params.setTotalCounts(count);
		resultMap.put("hospitalNotesJson", hospitalNotes);
		resultMap.put("medRecordQuery", params);
		if(hospitalNotes!=null && hospitalNotes.size()>0){
			result= new Result(true, "查询成功!",resultMap);
		}else{
			result= new Result(false, "暂无数据!",resultMap);
		}
		
		return result;
	}
	
	/**
	 * 病案检索 mobile
	 * 
	 * @return
	 */
	@PostMapping("/ajaxMedicalSearch")
	@ResponseBody
	public Result ajaxMedicalSearch(@RequestParam(value = "page", defaultValue = "1") int currentPage,
			HttpServletRequest request) {
		Map<String, Object> params = new HashMap<>();
		
		try {
			Page page = new Page();
			page.setCurrentPage(currentPage);
			page.setPageSize(10);
			page.setCurrentPage(currentPage);
			params.put("mrId", request.getParameter("mrId"));
			params.put("name", request.getParameter("name"));
			params.put("idCard", request.getParameter("idCard"));
			params.put("outHospitalStartDate", request.getParameter("outHospitalStartDate"));
			params.put("outHospitalEndDate", request.getParameter("outHospitalEndDate"));
			params.put("outHospitalOfficeId",  request.getParameter("outHospitalOfficeId"));
			params.put("page", page);
			
			List<Map<String, Object>> list = medRecordService.getMedicalSearchListPage(params);
			page.setList(list);
			page.setRows(medRecordService.getMedicalSearchCountPage(params));
			System.out.println("---------------请求参数---" + params);
			
			return new Result(true, "查询成功!", page);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("病案检索查询失败: --- " + ExceptionUtil.getStackTrace(e));
			return new Result(false, "查询失败!", null, 500);
		}
		
	}
	
	@GetMapping("/exportQualitySearchToExcel")
	public void exportQualitySearchToExcel(MedRecordQuery params,HttpServletResponse response){
		List<Map<String,Object>> scanWorkMapList = new ArrayList<>();
		try {
			response.setContentType("octets/stream");
	        String excelName = "质控评价";  
			//转码防止乱码  
			response.addHeader("Content-Disposition", "attachment;filename="+new String(excelName.getBytes("gb2312"), "ISO8859-1" )+".xls");  
			//通过response获取文件输出流
			OutputStream out = response.getOutputStream();
		
			//查询数据
			scanWorkMapList=medRecordService.exportBorrowToExcel(params);
			System.out.println(scanWorkMapList.size());
			String title="质控评价";
			String[] header={"病案号","姓名","证件号码","出院科室","出院日期","离院方式"};
			ExcelUtil.exportExcel(out, title, header, scanWorkMapList);
			
		} catch (Exception e) {
			e.printStackTrace();
			
		}
		
	}
	//导出病案借阅到excel
	@GetMapping("/exportBorrowToExcel")
	public void exportBorrowToExcel(MedRecordQuery params,HttpServletResponse response){
		List<Map<String,Object>> scanWorkMapList = new ArrayList<>();
		try {
			response.setContentType("octets/stream");
	        String excelName = "病案借阅";  
			//转码防止乱码  
			response.addHeader("Content-Disposition", "attachment;filename="+new String(excelName.getBytes("gb2312"), "ISO8859-1" )+".xls");  
			//通过response获取文件输出流
			OutputStream out = response.getOutputStream();
		
			//查询数据
			scanWorkMapList=medRecordService.exportBorrowToExcel(params);
			System.out.println(scanWorkMapList.size());
			String title="病案借阅";
			String[] header={"病案号","姓名","身份证号","出院科室","出院日期","离院方式"};
			ExcelUtil.exportExcel(out, title, header, scanWorkMapList);
			
		} catch (Exception e) {
			e.printStackTrace();
			
		}
	}
	
	//@RequiresPermissions("pigeonholed")
	@GetMapping("/pigeonholed")
	public String pigeonholed(MedRecordQuery params,Model model){
		LeftMenuPojo leftMenu = LeftMenuPojo.GetLeftMenu("collection_module");
		String leftMenuJson = JsonUtils.objectToJson(leftMenu);
		List<Map<String,Object>> medicalOffices = basicInfoService.getMedicalOfficesByHospitalId(1);
		model.addAttribute("basicInfo", basicInfoService.getSimpleBasicInfos());
		List<Map<String,Object>> hospitalNotes = new ArrayList<Map<String,Object>>();
		
		if (!params.IsPropertyEmpty()) {
			hospitalNotes = medRecordService.getPigeonholed(params);
		}
		
		int count = medRecordService.getPigeonholedCount(params);
		params.setTotalCounts(count);
		
		model.addAttribute("hospitalNotesJson", JsonUtils.objectToJson(hospitalNotes));
		model.addAttribute("pageJson", JsonUtils.objectToJson(params));
		model.addAttribute("leftMenuJson", leftMenuJson);
		model.addAttribute("medRecordQuery", params);
		model.addAttribute("offices", medicalOffices);
		
		return "medrecord/pigeonholed.page";
	}
	
	@GetMapping("/exportunPigeonholeToExcel")
	public void exportunPigeonholeToExcel(MedRecordQuery params,HttpServletResponse response){
		List<Map<String,Object>> scanWorkMapList = new ArrayList<>();
		try {
			response.setContentType("octets/stream");
	        String excelName = "未归病案";  
			//转码防止乱码  
			response.addHeader("Content-Disposition", "attachment;filename="+new String(excelName.getBytes("gb2312"), "ISO8859-1" )+".xls");  
			//通过response获取文件输出流
			OutputStream out = response.getOutputStream();
		
			//查询数据
			scanWorkMapList=medRecordService.exportUnPigeonholeToExcel(params);
			System.out.println(scanWorkMapList.size());
			String title="未归病案";
			String[] header={"姓名","身份证号","病案号","出院日期","出院科室","离院方式","状态"};
			ExcelUtil.exportExcel(out, title, header, scanWorkMapList);
			
		} catch (Exception e) {
			e.printStackTrace();
			
		}
	}
	
	@GetMapping("/completePigeonholeForm")
	public String completePigeonholeForm(String guid,Model model){
		if (StringUtil.isEmpty(guid)) {
			return "redirect:/medrecord/unPigeonhole";
		}
		
		List<Map<String,Object>> hospitalNotes = medRecordService.getHospitalizationNoteBasicByFirstGuid(guid);
		
		if (hospitalNotes.size() < 1) {
			return "redirect:/medrecord/unPigeonhole";
		}
		
		Map<String,Object> hospitalNote = hospitalNotes.get(0);
		LeftMenuPojo leftMenu = LeftMenuPojo.GetLeftMenu("collection_module");
		String leftMenuJson = JsonUtils.objectToJson(leftMenu);
		model.addAttribute("leftMenuJson", leftMenuJson);
		model.addAttribute("hospitalNote", hospitalNote);
		model.addAttribute("guid", guid);
		model.addAttribute("currentDateTime", new Date());
		
		return "medrecord/completePigeonhole.page";
	}
	
	@ResponseBody
	@PostMapping("/ajaxCompletePigeonhole")
	public Result ajaxCompletePigeonholes(String guid,String traceDateTime,Integer specialIndication,HttpServletRequest request){
		Result result = null;
		String currentUser = CookieUtils.getCookieValue(request, "userName");
		medicalRecordService.updateHospitalizationSpecialIndication(guid,specialIndication);
		try {
			if(StringUtils.isEmpty(guid)){
				result = new Result(false,"guid不能为空!");
				return result;
			}
			TreatmentTrace treatmentTrace = new TreatmentTrace();
			treatmentTrace.setTraceTypeId(2);
			treatmentTrace.setTreatmentGuid(guid);
			treatmentTrace.setUserId(currentUser);
			treatmentTrace.setTraceDate(DateUtil.dateParse(DateUtil.DATE_TIME_FORMATE, traceDateTime));
			treatmentTraceService.addMedicalTrace(treatmentTrace,TreatmentTrace.VISIT_PIGEONHOLE);
			return new Result(true,"归档完成!");
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false,"归档失败!");
		}
	}
	
	@PostMapping("/completePigeonhole")
	public String completePigeonhole(String guid,String traceDateTime,Model model,HttpServletRequest request){
		if (StringUtil.isEmpty(guid)) {
			return "redirect:/medrecord/unPigeonhole";
		}
		
		List<Map<String,Object>> hospitalNotes = medRecordService.getHospitalizationNoteBasicByFirstGuid(guid);
		
		if (hospitalNotes.size() < 1) {
			return "redirect:/medrecord/unPigeonhole";
		}
		
		Map<String,Object> hospitalNote = hospitalNotes.get(0);
		String currentUser = CookieUtils.getCookieValue(request, "TT_TOKEN");
		TreatmentTrace treatmentTrace = new TreatmentTrace();
		treatmentTrace.setTraceTypeId(2);
		treatmentTrace.setTreatmentGuid(guid);
		treatmentTrace.setUserId(currentUser);
		
		
		try {
			treatmentTrace.setTraceDate(DateUtil.dateParse(DateUtil.DATE_TIME_FORMATE, traceDateTime));
		} catch (ParseException e) {
			log.error(ExceptionUtil.getStackTrace(e));
			e.printStackTrace();
			treatmentTrace.setTraceDate(new Date());
		}
		
		treatmentTraceService.addMedicalTrace(treatmentTrace,TreatmentTrace.VISIT_PIGEONHOLE);
		LeftMenuPojo leftMenu = LeftMenuPojo.GetLeftMenu("collection_module");
		String leftMenuJson = JsonUtils.objectToJson(leftMenu);
		model.addAttribute("leftMenuJson", leftMenuJson);
		model.addAttribute("hospitalNote", hospitalNote);
		
		return "redirect:/medrecord/pigeonholed?mrId="+hospitalNote.get("mr_id").toString();
	}
	
	
	@GetMapping("/pigeonholeCheck")
	public String pigeonholeCheck(MedTraceQuery params, Model model){
		LeftMenuPojo leftMenu = LeftMenuPojo.GetLeftMenu("collection_module");
		String leftMenuJson = JsonUtils.objectToJson(leftMenu);
		List<Map<String,Object>> medicalOffices = basicInfoService.getMedicalOfficesByHospitalId(1);
		model.addAttribute("basicInfo", basicInfoService.getSimpleBasicInfos());
		List<Map<String,Object>> hospitalNotes = new ArrayList<Map<String,Object>>();
		
		if (!params.IsPropertyEmpty()) {
			hospitalNotes = medRecordService.getPigeonholeCheck(params);
		}
		
		model.addAttribute("hospitalNotesJson", JsonUtils.objectToJson(hospitalNotes));
		model.addAttribute("pageJson", JsonUtils.objectToJson(params));
		model.addAttribute("leftMenuJson", leftMenuJson);
		model.addAttribute("medTraceQuery", params);
		model.addAttribute("offices", medicalOffices);
		
		return "medrecord/pigeonholeCheck.page";
	}
	
	
	//@RequiresPermissions("urge")
	@GetMapping("/urgeList")
	public String urgeList(MedVisitUrgeQuery params, Model model){
		LeftMenuPojo leftMenu = LeftMenuPojo.GetLeftMenu("collection_module");
		String leftMenuJson = JsonUtils.objectToJson(leftMenu);
		List<Map<String,Object>> medicalOffices = basicInfoService.getMedicalOfficesByHospitalId(1);
		model.addAttribute("basicInfo", basicInfoService.getSimpleBasicInfos());
		List<Map<String,Object>> hospitalNotes = new ArrayList<Map<String,Object>>();
		
		if (!params.IsPropertyEmpty()) {
			hospitalNotes = medRecordService.getMedicalVisitOfUrge(params);
		}
		
		model.addAttribute("hospitalNotesJson", JsonUtils.objectToJson(hospitalNotes));
		model.addAttribute("pageJson", JsonUtils.objectToJson(params));
		model.addAttribute("leftMenuJson", leftMenuJson);
		model.addAttribute("medVisitUrgeQuery", params);
		model.addAttribute("offices", medicalOffices);
		
		return "medrecord/urge.page";
	}
	
	
	@PostMapping("/urge")
	public String urge(String[] urgeGuids, MedVisitUrgeQuery params, Model model, HttpServletRequest request){
		String currentUser = CookieUtils.getCookieValue(request, "userName");
		medRecordService.medicalVisitUrge(urgeGuids,currentUser,params.getByUrgeUserPhone());
		LeftMenuPojo leftMenu = LeftMenuPojo.GetLeftMenu("collection_module");
		String leftMenuJson = JsonUtils.objectToJson(leftMenu);
		List<Map<String,Object>> medicalOffices = basicInfoService.getMedicalOfficesByHospitalId(1);
		model.addAttribute("basicInfo", basicInfoService.getSimpleBasicInfos());
		List<Map<String,Object>> hospitalNotes = new ArrayList<Map<String,Object>>();
		
		if (!params.IsPropertyEmpty()) {
			hospitalNotes = medRecordService.getMedicalVisitOfUrge(params);
		}
		
		model.addAttribute("hospitalNotesJson", JsonUtils.objectToJson(hospitalNotes));
		model.addAttribute("pageJson", JsonUtils.objectToJson(params));
		model.addAttribute("leftMenuJson", leftMenuJson);
		model.addAttribute("medVisitUrgeQuery", params);
		model.addAttribute("offices", medicalOffices);
		
		return "medrecord/urge.page";
	}
	
	
	@PostMapping("/addQualityTraceAjax")
	@ResponseBody
	public Result addQualityTraceAjax(TreatmentTrace treatmentTrace,Model model,HttpServletRequest request){
		Map<String,Object> resultMap = new HashMap<String, Object>();
		String currentUser = CookieUtils.getCookieValue(request, "userName");
		
		System.out.println("userId"+treatmentTrace.getUserId());
		
		try {
			currentUser =URLDecoder.decode(treatmentTrace.getUserId(), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		treatmentTrace.setUserId(currentUser);
		int resultCount = medRecordService.addQualityTrace(treatmentTrace);
		Result result = null;
		
		if (resultCount == 1) {
			 result= new Result(true, "操作成功!", resultMap);
		} else {
			result= new Result(false, "操作失败!", resultMap);
			log.error("addQualityTraceAjax--------操作失败!");
		}
		
		return result;
	}
	
	
	@ResponseBody
	@RequestMapping("/manualReviewAjax")
	public Result manualReviewAjax(MedRecordQuery params,HttpServletResponse response){
		response.setHeader("Access-Control-Allow-Origin", "*");
		Result result = null;
		
		try {
			Map<String,Object> map = new HashMap<String, Object>();
			List<Map<String,Object>> list = medRecordService.getHospitalizationNoteList(params);
			int count = medRecordService.getHospitalizationNoteCount(params);
			map.put("auditList", list);
			map.put("count", count);
			map.put("auditQuery", params);
			
			result=new Result(true,"查询成功!",map);
		} catch(Exception e) {
			log.error("manualReviewAjax查询失败---"+ExceptionUtil.getStackTrace(e));
			e.printStackTrace();
			result=new Result(false,"查询失败!");
		}
		
		return result;
	}
	
	@ResponseBody
	@RequestMapping("/getManualReviewBasicDataAjax")
	public Result getManualReviewBasicDataAjax(HttpServletResponse response){
		response.setHeader("Access-Control-Allow-Origin", "*");
		Result result = null;
		
		try {
			Map<String,Object> map = new HashMap<String, Object>();
			map.put("outHosTypes",  basicInfoService.getOutHospitalTypes());
			map.put("offices", basicInfoService.getMedicalOfficesByHospitalId(1));
			
			result=new Result(true,"查询成功!",map);
		} catch(Exception e) {
			log.error("getManualReviewBasicDataAjax----查询失败"+ExceptionUtil.getStackTrace(e));
			e.printStackTrace();
			result=new Result(false,"查询失败!");
		}
		
		return result;
	}




	/**
	 * 文件上传
	 * @param params
	 * @param model
	 * @return
	 */
	@GetMapping("/medRecordFileUpload")
	public String medRecordFileUpload(MedRecordQuery params,Model model){
		LeftMenuPojo leftMenu = LeftMenuPojo.GetLeftMenu("add_module");
		String leftMenuJson = JsonUtils.objectToJson(leftMenu);
		List<Map<String,Object>> medicalOffices = basicInfoService.getMedicalOfficesByHospitalId(1);
		model.addAttribute("basicInfo", basicInfoService.getSimpleBasicInfos());
		List<Map<String,Object>> hospitalNotes = new ArrayList<Map<String,Object>>();
		
		if (!params.IsPropertyEmpty()) {
			hospitalNotes = medRecordService.getUnPigeonhole(params);
		}
		
		int count = medRecordService.getUnPigeonholeCount(params);
		params.setTotalCounts(count);
		
		model.addAttribute("hospitalNotesJson", JsonUtils.objectToJson(hospitalNotes));
		model.addAttribute("pageJson", JsonUtils.objectToJson(params));
		model.addAttribute("leftMenuJson", leftMenuJson);
		model.addAttribute("medRecordQuery", params);
		model.addAttribute("offices", medicalOffices);
		
		return "medrecord/medRecordFileUpload.page";
	}
	
	/**
	 * 文件上传查询病案信息
	 * @param medicalSearchQuery
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getMedRecordList")
	public Result getMedRecordList(MedicalSearchQuery medicalSearchQuery){
		log.info("----------进入上传文件查询病案数据----------");
		Result result =null;
		try {
			Map<String,Object> map = new HashMap<>();
			List<Map<String,Object>> medRecordList=medRecordService.getMedRecordList(medicalSearchQuery);
			int totalCount = medRecordService.getMedRecordListCount(medicalSearchQuery);
			map.put("medRecordList", medRecordList);
			map.put("totalCount", totalCount);
			result = new Result(true,"病案数据查询成功!",map);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("上传文件查询病案数据出现异常:"+e.getMessage());
		}
		return result;
	}
	
	
	//跳转到文件上传
//	@RequestMapping("/uploadFile")
//	public String uploadFile(Model model,String firstGuid){
//		LeftMenuPojo leftMenu = LeftMenuPojo.GetLeftMenu("add_module");
//		String leftMenuJson = JsonUtils.objectToJson(leftMenu);
//		model.addAttribute("leftMenuJson", leftMenuJson);
//		Map<String,Object> hospitalNote=medRecordService.getHospitalNoteByFirstGuid(firstGuid);
//		model.addAttribute("hospitalNote", hospitalNote);
//		return "upload/uploadFile";
//	}
	
	
	/**
	 * 文件上传
	 * @param params
	 * @param model
	 * @return
	 */
	@GetMapping("/uploadFile")
	public String uploadFile(Model model,String firstGuid){
		LeftMenuPojo leftMenu = LeftMenuPojo.GetLeftMenu("add_module");
		String leftMenuJson = JsonUtils.objectToJson(leftMenu);
		List<Map<String,Object>> medicalOffices = basicInfoService.getMedicalOfficesByHospitalId(1);
		model.addAttribute("basicInfo", basicInfoService.getSimpleBasicInfos());
		List<Map<String,Object>> hospitalNotes = new ArrayList<Map<String,Object>>();
		
		//LeftMenuPojo leftMenu = LeftMenuPojo.GetLeftMenu("add_module");
		//String leftMenuJson = JsonUtils.objectToJson(leftMenu);
		//model.addAttribute("leftMenuJson", leftMenuJson);
		Map<String,Object> hospitalNote=medRecordService.getHospitalNoteByFirstGuid(firstGuid);
		model.addAttribute("hospitalNote", hospitalNote);
		
		model.addAttribute("hospitalNotesJson", JsonUtils.objectToJson(hospitalNotes));
		//model.addAttribute("pageJson", JsonUtils.objectToJson(params));
		//model.addAttribute("leftMenuJson", leftMenuJson);
		//model.addAttribute("medRecordQuery", params);
		model.addAttribute("offices", medicalOffices);
		
		return "upload/uploadFile";
	}

	
//	@RequestMapping("/queryMedrecordVersion")
//	public String queryMedrecordVersion(MedRecordQuery params, Model model){
//		LeftMenuPojo leftMenu = LeftMenuPojo.GetLeftMenu("query_module");
//		String leftMenuJson = JsonUtils.objectToJson(leftMenu);
//		List<Map<String,Object>> hospitalizationNotes = medRecordService.getHospitalizationNoteList(params);
//		int count = medRecordService.getHospitalizationNoteCount(params);
//		params.setTotalCounts(count);
//		model.addAttribute("hospitalizationNotes", hospitalizationNotes);
//		model.addAttribute("leftMenuJson", leftMenuJson);
//		model.addAttribute("medRecordQuery", params);
//		
//		return "query/queryMedrecordVersion";
//	}
	
	
	@GetMapping("/queryMedrecordVersion")
	public String queryMedrecordVersion(MedRecordQuery params,Model model){
		LeftMenuPojo leftMenu = LeftMenuPojo.GetLeftMenu("query_module");
		String leftMenuJson = JsonUtils.objectToJson(leftMenu);
		List<Map<String,Object>> medicalOffices = basicInfoService.getMedicalOfficesByHospitalId(1);
		model.addAttribute("basicInfo", basicInfoService.getSimpleBasicInfos());
		
		model.addAttribute("leftMenuJson", leftMenuJson);
		model.addAttribute("offices", medicalOffices);
		
		return "query/queryMedrecordVersion.page";
	}
    
	@GetMapping("/queryMedrecordVersion_V")
	public String queryMedrecordVersion_V(MedRecordQuery params,Model model){
		LeftMenuPojo leftMenu = LeftMenuPojo.GetLeftMenu("query_module");
		String leftMenuJson = JsonUtils.objectToJson(leftMenu);
		List<Map<String,Object>> medicalOffices = basicInfoService.getMedicalOfficesByHospitalId(1);
		model.addAttribute("basicInfo", basicInfoService.getSimpleBasicInfos());
		
		model.addAttribute("leftMenuJson", leftMenuJson);
		model.addAttribute("offices", medicalOffices);
		
		return "query/queryMedrecordVersion_V.page";
	}
	
//	@RequestMapping("/medrecordHomePageVersionManage")
//	public String medrecordHomePageVersionManage(String firstGuid,String guid,Model model){
//		List<Map<String,Object>> hospitalizationNotes = medRecordService.getHospitalizationNoteBasicByFirstGuid(firstGuid);
//		if(hospitalizationNotes.size() > 0){
//			model.addAttribute("hospitalizationNote", hospitalizationNotes.get(0));
//		}
//		Map<String, List<Map<String,Object>>> basicInfoMap = basicInfoService.getBasicInfos();
//		basicInfoMap.put("offices", basicInfoService.getMedicalOfficesByHospitalId(1));
//		model.addAttribute("basicInfos", basicInfoMap);
///*		String filePath = conf.getHospitalizationNoteResourcePath();
//		String fileName = firstGuid + ".txt";*/
//		HospitalizationNoteBasic noteBasic = null;
//		try {
//			//Map<String, String> jsonMap = readLineFile(filePath,fileName);
//			
//			//根据firstGuid查询住院基本信息
//			//String hosBasicJson=hospNoteBasicJsonService.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(firstGuid));
//			HospitalNoteVersion hospitalNoteVersion = hospitalNoteVersionService.findHospitalNoteVersionByGuid(guid);
//			String hosBasicJson=null;
//			if(hospitalNoteVersion!=null){
//				hosBasicJson = hospitalNoteVersion.getHospitlNoteJson();
//			}
//			Map<String, Object> jsonMap =this.getHospBasicJson(hosBasicJson);
//			 if(jsonMap.get("hospitalizationNoteBasic")!=null){
//			        noteBasic= JsonUtils.jsonToPojo(JsonUtils.objectToJson(jsonMap.get("hospitalizationNoteBasic")),HospitalizationNoteBasic.class) ;
//		      }
//			addMedrecordHomePageInfo(model,jsonMap);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		model.addAttribute("noteBasic", noteBasic);
//		return "medrecord/medRecordHomePageManage.simple";
//	}
	
	
	@ResponseBody
	@RequestMapping("/validateDiagCodeBind")
	public Result validateDiagCodeBind(String diagCodes){
		Result result = null;
		
		try {
			String ret= medRecordService.diagAssociationCode(diagCodes);
			if(StringUtils.isEmpty(ret)){
				result = new Result(false);
			}else{
				result = new Result(true,ret);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 删除病案记录
	 * @param firstGuid
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/deleteMedicalRecord")
	public Result deleteMedicalRecord(String firstGuid) {
		Result result = null;
		try {
			medRecordService.deleteMedicalRecord(firstGuid);
			result = new Result(true);
		} catch (Exception e) {
			e.printStackTrace();
			result = new Result(false);
		}
		return result;
	}
	
	@ResponseBody
	@RequestMapping("/imgSort")
	public Result imgSort(String fileHash,String sortIndex) {
		Result result = null;
		try {
			medRecordService.updateScanFilrOriginalName(fileHash,sortIndex);
			result = new Result(true);
		} catch (Exception e) {
			e.printStackTrace();
			result = new Result(false);
			
		}
		return result;
	}
	
	
	/**
	 * ajax 通过mrId和visitNumber查询病案
	 * @param params
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/queryMedrecordOfMailPrintByAjax",method=RequestMethod.GET)
	@ResponseBody
	public Result queryMedrecordOfMailPrintByAjax(String visitNumber, String mrId, Model model, HttpServletResponse response){
		response.setHeader("Access-Control-Allow-Origin", "*");
		try {
			List<Map<String, Object>> list = medRecordService.getHospNoteByMrIdAndVisitNumber(mrId, visitNumber);
			return new Result(true, "查询成功!", list);
		} catch (Exception e) {
			log.error("---通过mrId和visitNumber查询病案失败--- " + ExceptionUtil.getStackTrace(e));
			return new Result(false, "查询失败!", null, 500);
		}
	}
	
	/**
	 * 扫描编页工作量统计
	 * 
	 * @param name
	 * @param scanStartDate
	 * @param scanEndDate
	 * @param response
	 * @return
	 */
	@GetMapping("/queryPaginationWorkStatisticAjax")
	@ResponseBody
	public Result queryPaginationWorkStatisticAjax(String name, String scanStartDate, String scanEndDate, HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		
		try {
			
			int count = scanFileService.getPaginationScanWorkStaticCountByNameAndScanDate(name, scanStartDate, scanEndDate);
			return new Result(true, "查询成功", count);
		} catch (Exception e) {
			log.error("---病案编页工作量统计异常--- " + ExceptionUtil.getStackTrace(e));
			return new Result(false, "查询失败" + ExceptionUtil.getStackTrace(e), null, 500);
		}
		
	}
	
	
	@ResponseBody
	@PostMapping("/deleteCertainPageTypeImgs")
	public Result deleteCertainPageTypeImgs(String firstGuid, Integer pageTypeId){
		Result result = null;
		
		try{
			if (StringUtils.isNotBlank(firstGuid)) {
				if (null != pageTypeId) {
					medicalResourceService.deleteCertainPageTypeImgs(firstGuid, pageTypeId);
				} else {
					//删除所有扫描图片
					medicalResourceService.deleteAllScanImages(firstGuid);
				}
			}
			result = new Result(true, "删除成功");
		}catch (Exception e) {
			e.printStackTrace();
			log.error("----删除某个标签对应的所有图片失败-----firstGuid="+firstGuid + " pageTypeId="+pageTypeId + ExceptionUtil.getStackTrace(e));
			result = new Result(false, "删除失败"+ExceptionUtil.getStackTrace(e));
		}
		
		return result;
		
	}
	
	
	/**
	 * 重复提取检验报告单
	 * 
	 * @param visitGuid
	 * @param mrId
	 * @param visitNumber
	 * @param request
	 * @param response
	 * @return
	 */
	@GetMapping("/ajaxRepeatFetchExaminationReportsInfoByMrIdAndVisitNumber")
	@ResponseBody
	public Result ajaxRepeatFetchExaminationReportsInfoByMrIdAndVisitNumber(String visitGuid, String mrId, Integer visitNumber, 
			HttpServletRequest request, HttpServletResponse response) {
		String dateStr = DateUtil.dateFormat("yyyyMMddHHmmssssss", new Date());
		Map<String, String> params = new HashMap<String, String>();
		params.put("visitGuid", visitGuid);
		params.put("mrId", mrId);
		params.put("visitNumber", visitNumber+"");
		params.put("dateStr", dateStr);
		String url = myConfig.getExportProjectUrl() + "export305/ajaxRepeatFetchExaminationReportsInfoByMrIdAndVisitNumber";
		String export305Result = HttpClientUtil.doGet(url, params);
		
		if (StringUtils.isBlank(export305Result)) {
			return new Result(false, "export服务没有启动!");
		}
		
		Result remoteResult = (Result) JsonUtil.jsonToPojo(export305Result, Result.class);
		if (!remoteResult.isSuccess()) {
			return remoteResult;
		}
		
		Map<String, Object> examinationReportsInfo = JsonUtil.jsonToPojo((String)remoteResult.getData(), Map.class);
		
		//更新json里面的病程记录
		String preFileName = visitGuid + "_" + mrId + "_" + visitNumber + "_";
		String filePath = myConfig.getHospitalVisitJsonPath() + StringUtil.getLocalPath(visitGuid);
		String fileName = visitGuid + ".json";
		String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + visitGuid + "/";
		// 版本文件名称
		String versionFileName = dateStr + ".json";

		
		String diskName = DiskManageUtil.getDiskNameByFileName(config.getConfigFileStorageAllDisk(), filePath + fileName);
		
		if (StringUtils.isBlank(diskName)) {
			log.error("本地磁盘{}里面没有找到json文件, filePath={}, visitGuid", config.getConfigFileStorageAllDisk(), 
					filePath + fileName, visitGuid);
			return new Result(false, "本地json文件没有找到!", null, 500);
		} 
		
		
		//写入到本地json文件
		String realFilePath = diskName + filePath.trim().substring(1);
		
		//to do
		Map<String, Object> jsonMap = FileUtil.readLineFile(realFilePath, fileName);
		
		
		String currentUser = CookieUtils.getCookieValue(request, "userName");
		jsonMap.put("userId", currentUser);
		jsonMap.put("examinationReportsInfo", examinationReportsInfo);
		String jsonMapJson = JsonUtil.objectToJson(jsonMap);
		
			
			try {
				FileUtil.createOrEditFile(jsonMapJson, realFilePath, fileName);
			} catch (IOException io) {
				//保存本地json文件失败 
				ExceptionLog exceptionLog = new ExceptionLog();
				exceptionLog.setLogContent("保存本地json文件失败----" + ExceptionUtil.getStackTrace(io));
				exceptionLog.setLogFilePath(myConfig.getExaminationLocalDir()+"log");
				exceptionLog.setLogFileName(preFileName + dateStr + ".log");
				exceptionLog.writeLog();
				return new Result(false, "保存本地json文件异常  "+ExceptionUtil.getStackTrace(io), null, 500);
			}
			
			try {
				FileUtil.createOrEditFile(jsonMapJson, versionFilePath, versionFileName);
			} catch (IOException io) {
				//保存本地json文件失败  这个可以手动去同步
				ExceptionLog exceptionLog = new ExceptionLog();
				exceptionLog.setLogContent("保存本地json版本文件失败----jsonMapJson=" + jsonMapJson + " versionFilePath=" + versionFilePath + 
						" versionFileName="+versionFileName + ExceptionUtil.getStackTrace(io));
				exceptionLog.setLogFilePath(myConfig.getExaminationLocalDir()+"log");
				exceptionLog.setLogFileName(preFileName + dateStr+"_saveLocalJsonFile" + ".log");
				exceptionLog.writeLog();
				//删除已经保存病程记录html
			}
			
			//记录版本
			HospNoteVersion hospNoteVersion = new HospNoteVersion();
			try {
				hospNoteVersion.setCreateTime(new Date());
				hospNoteVersion.setFirstGuid(visitGuid);
				hospNoteVersion.setFileName(versionFileName);
				hospNoteVersion.setOperator(currentUser);
				hospitalNoteVersionService.insertHospitalNoteVersion(hospNoteVersion);
			} catch (Exception e) {
				ExceptionLog exceptionLog = new ExceptionLog();
				exceptionLog.setLogContent("---hospNoteVersion保存到数据库失败--visitGuid=" + visitGuid + 
						" versionFileName=" + versionFileName + " currentUser=" +currentUser);
				exceptionLog.setLogFilePath(myConfig.getExaminationLocalDir()+"log");
				exceptionLog.setLogFileName(preFileName + dateStr+"_insertHospNoteVersionDataBase" + ".log");
				exceptionLog.writeLog();
			}
			
			String hospitalVisitDataJson = null;
			try {
				hospitalVisitDataJson = hospNoteBasicJsonService.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitGuid));
			} catch (Exception e) {
				//需要删除本地json版本和数据库版本
				ExceptionLog exceptionLog = new ExceptionLog();
				exceptionLog.setLogContent("查询导致数据库系统异常  visitGuid="+ visitGuid + " hospNoteVersionId=" + hospNoteVersion.getId()
						+ " versionFilePath=" + versionFilePath + " versionFileName=" + versionFileName
						+ ExceptionUtil.getStackTrace(e) );
				exceptionLog.setLogFilePath(myConfig.getExaminationLocalDir()+"log");
				exceptionLog.setLogFileName(preFileName + dateStr+ "_selectHospNoteBasicJsonDatabase"+ ".log");
				exceptionLog.writeLog();
				return new Result(false, "查询数据库json导致数据库系统异常"+ExceptionUtil.getStackTrace(e), null, 500);
			}
			
			Map<String, Object> jsonDataMap = new HashMap<String, Object>();
			
			//保存检验报告单记录到数据库json中
			if (hospitalVisitDataJson != null) {
				jsonDataMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
				jsonDataMap.put("examinationReportsInfo", examinationReportsInfo);
				
				try {
					hospNoteBasicJsonService.updateHospBasicJsonByFirstGuid(visitGuid,
							JsonUtils.objectToJson(jsonDataMap));
				} catch (Exception e) {
					//需要删除本地json版本和数据库版本
					ExceptionLog exceptionLog = new ExceptionLog();
					exceptionLog.setLogContent("写入数据库异常  visitGuid="+ visitGuid + " hospNoteVersionId=" + hospNoteVersion.getId()
							+ " versionFilePath=" + versionFilePath + " versionFileName=" + versionFileName
							+ ExceptionUtil.getStackTrace(e) );
					exceptionLog.setLogFilePath(myConfig.getExaminationLocalDir()+"log");
					exceptionLog.setLogFileName(preFileName + dateStr+ "_insertHospNoteBasicJsonDatabase"+ ".log");
					exceptionLog.writeLog();
					return  new Result(false, "保存检验报告单记录到数据库json中系统异常"+ExceptionUtil.getStackTrace(e), null, 500);
				} 
				
			} else {
				jsonDataMap.put("firstGuid", visitGuid);
				jsonDataMap.put("examinationReportsInfo", examinationReportsInfo);
				
				try {
					hospNoteBasicJsonService.addHospNoteBasicJson(JsonUtils.objectToJson(jsonDataMap));
				} catch (Exception e) {
					ExceptionLog exceptionLog = new ExceptionLog();
					exceptionLog.setLogContent("写入数据库异常  visitGuid="+ visitGuid + " hospNoteVersionId=" + hospNoteVersion.getId()
					+ " versionFilePath=" + versionFilePath + " versionFileName=" + versionFileName
					+ ExceptionUtil.getStackTrace(e) );
					exceptionLog.setLogFilePath(myConfig.getExaminationLocalDir()+"log");
					exceptionLog.setLogFileName(preFileName + dateStr + "_insertHospNoteBasicJsonDatabase" + ".log");
					exceptionLog.writeLog();
					return new Result(false, "保存检验报告单记录到数据库json中"+ExceptionUtil.getStackTrace(e), null, 500);
				}
		   }
	
			//检验报告单转化成图片		
			Map<String, Object> jsonMap1 = FileUtil.readLineFile(filePath, fileName);
			if (jsonMap != null) {
				Map<String, Object> examMap = (Map<String, Object>) jsonMap.get("examinationReportsInfo");
				if (examMap != null) {
					List<Map<String, Object>> examinationRecords = (List<Map<String, Object>>) examMap.get("examinationReportsRecords");
					
					if (null != examinationRecords && examinationRecords.size() > 0) {
						List<List<Map<String, Object>>> lists = ListUtil.split(examinationRecords, 2);
						List<String> pdfPathList = new ArrayList<>();
						File tempfile = new File(config.getExaminationPdfPath() + "temp/");

						if (!tempfile.exists()) {
							tempfile.mkdirs();
						}

						for (int i = 0; i < lists.size(); i++) {
							String guidStr = StringUtil.getId();
							PDFUtil.getPdfByTemplate(lists.get(i), config.getExaminationPdfPath() + "template.pdf",
									config.getExaminationPdfPath() + "temp/pdf" + guidStr + ".pdf");
							pdfPathList.add(config.getExaminationPdfPath() + "temp/pdf" + guidStr + ".pdf");
						}

						File file = new File(config.getUploadResourcePath() + "examination/" + visitGuid + "/");
						
						if (!file.exists()) {
							file.mkdirs();
						}
						
						List<String> pdfImageList = PDFUtil.pdf2Image(pdfPathList,
								config.getUploadResourcePath() + "/examination/" + visitGuid + "/");
						
						medicalRecordService.addMedicalResourceExaminationForScan(pdfImageList, currentUser, visitGuid,config.getUploadResourcePath() + "/examination/" + visitGuid + "/");
						//删除并发产生的数据
						medicalRecordService.deleteMreByGroupId(visitGuid, config.getUploadResourcePath() + "/examination/" + visitGuid + "/");
					}
				}
			}
			
			return new Result(true, "success", null, 200);
		
	}
	
	
	@GetMapping("/copeLocalJsonToDataBaseAjax")
	@ResponseBody
	public Result copeLocalJsonToDataBase() {
		Result result = null;
		
		try {
			List<FirstLevelMedical> firstLevelList = firstLevelMedicalService.getFirstLevelMedicalList();
			
			for (FirstLevelMedical fl : firstLevelList) {
				String firstGuid = fl.getGuid();
				String path = "D:\\publics\\hospital\\visit\\json\\" + StringUtil.getLocalPath(firstGuid) + firstGuid + ".json";
				File file = new File(path);
				
				if (!file.exists()) {
					System.out.println("firstGuide=" + firstGuid + "文件不存在!");
					continue;
				}
				
				//读取本地json文件
				String hospNoteBasicJsonStr = IOUtils.toString(new FileInputStream(file), "utf-8");
				
				if (StringUtils.isNotBlank(hospNoteBasicJsonStr)) {
					hospNoteBasicJsonService.addHospNoteBasicJson(hospNoteBasicJsonStr);
				} else {
					System.out.println("读取到本地json文件firstGuide=" + firstGuid + " 内容为空!");
				}
				
			}
			
			return new Result(true, "添加成功");
		} catch (Exception e) {
			return new Result(false, "系统异常:" + ExceptionUtil.getStackTrace(e));
		}
		
	}
	
	
	

}









